I got the following error when trying to do the same thing as in the tutorial.
// Document.swift
import SwiftUI
import UniformTypeIdentifiers
extension UTType {
static let Test_ProjectDocument =
UTType(exportedAs: "com.testproject")
}
struct Test_ProjectDocument: FileDocument, Codable { // < "Type 'Test_ProjectDocument'
// does not conform to protocol
// 'FileDocument' "
// "Protocol requires initializer 'init(configuration)' with
// type '(configuration: Test_ProjectDocument.ReadConfiguration)'
// (aka '(configuration
// FileDocumentReadConfiguration)') (SwiftUI.FileDocument.init)"
// "Protocol requires function 'fileWrapper(configuration:)'
// with type '(Test_ProjectDocument.WriteConfiguration)
// throws -> FileWrapper' (aka
// '(FileDocumentWriteConfiguration) throws -> FileWrapper')
// (SwiftUI.FileDocument.fileWrapper)
// "Add stubs for conformance"
// (What this changes is detailed below)
var allClasses: [SchoolClass]
init() {
self.allClasses = []
}
static var readableContentTypes: [UTType] { [.Test_ProjectDocument] }
init(fileWrapper: FileWrapper, contentType: UTType) throws {
let data = fileWrapper.regularFileContents!
self = try JSONDecoder().decode(Self.self, from: data)
}
func write(to fileWrapper: inout FileWrapper, contentType: UTType) throws {
let data = try JSONEncoder().encode(self)
fileWrapper = FileWrapper(regularFileWithContents: data)
}
}
(Rest of data model and app struct)
import SwiftUI
import CoreServices
public struct SchoolClass : Hashable, Codable, Identifiable {
public var id: Int
var ClassStudents: String = "Hello D. World" // placeholder
}
import SwiftUI
@main
struct Test_ProjectApp: App {
var body: some Scene { // < "Type 'Test_ProjectDocument' does not conform to protocol 'FileDocument' "
DocumentGroup(newDocument: Test_ProjectDocument()) { file in
ContentView(document: file.$document)
}
}
}
This is what the suggested fix adds:
import SwiftUI
import UniformTypeIdentifiers
extension UTType {
static let Test_ProjectDocument =
UTType(exportedAs: "com.testproject")
}
struct Test_ProjectDocument: FileDocument, Codable {
//// Suggested fix
init(configuration: ReadConfiguration) throws {
<#code#>
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
<#code#>
}
////
var allClasses: [SchoolClass]
init() {
self.allClasses = []
}
static var readableContentTypes: [UTType] { [.Test_ProjectDocument] }
init(fileWrapper: FileWrapper, contentType: UTType) throws {
let data = fileWrapper.regularFileContents!
self = try JSONDecoder().decode(Self.self, from: data)
}
func write(to fileWrapper: inout FileWrapper, contentType: UTType) throws {
let data = try JSONEncoder().encode(self)
fileWrapper = FileWrapper(regularFileWithContents: data)
}
}