Of course if you do want to go down the document based app route, it's possible but it has some weirdness about it (mostly due to limitations with the FileDocument API). Because of the bizarre ways the document based API works, I'd still suggest using the file picker approach, despite this taking care of the sandbox access for you.
You're on the right lines with your code, but because the FileDocument API doesn't give you the URL, and there's no mechanism for loading a USDZ as an Entity from Data, you have to write the USDZ contents to a temporary directory that you can access from your app sandbox, and then load it using the standard mechanism.
This is demonstrated here: https://vimeo.com/922479510.
import RealityKit
import SwiftUI
import UniformTypeIdentifiers
struct USDDocumentLoaderDocument: FileDocument {
// The entity will hold the contents of the USDZ file.
//
var entity: Entity
static var readableContentTypes: [UTType] { [.usdz] }
init(configuration: ReadConfiguration) throws {
// Load the contents of the USDZ file.
//
guard let data = configuration.file.regularFileContents else {
throw CocoaError(.fileReadCorruptFile)
}
// Write the data to a temporary location.
//
let temporaryFile = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, conformingTo: .usdz)
try data.write(to: temporaryFile)
// Load the USDZ from the temporary file. This blocks, which isn't ideal.
//
self.entity = try Entity.load(contentsOf: temporaryFile)
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
throw CocoaError(.featureUnsupported)
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: