自定义UTI的SwiftUI .fileImporter解码报错问题求助
问题原因与解决方法
核心问题:JSON结构与解码目标不匹配
你导出的JSON数据是嵌套结构,顶层包含testData键,对应的值才是TestData对象:
{"testData":{"name":"name","id":"D4C4C9CC-B7A0-4F79-8803-BF8C720396FF","number":10}}
但你在导入时直接尝试将整个JSON解码为TestData类型,而TestData的编码结构是扁平的(直接包含id、name、number键),这就导致解码器找不到顶层的id键,抛出错误。
解决方法:解码为ExportHandler类型
因为你使用ExportHandler封装数据进行分享,导出的JSON结构对应ExportHandler的编码格式,所以导入时需要先解码为ExportHandler,再从中提取testData:
修改导入部分的代码:
let decodedHandler = try JSONDecoder().decode(ExportHandler.self, from: data) let decodedParcours = decodedHandler.testData // 现在可以正常使用decodedParcours了
完整修正后的导入代码段
case .success(let success): do { if success.startAccessingSecurityScopedResource() { let data = try Data(contentsOf: success) let str = String(data: data, encoding: .utf8) print("The data is available:", str) // 修正:先解码为ExportHandler let decodedHandler = try JSONDecoder().decode(ExportHandler.self, from: data) let decodedParcours = decodedHandler.testData print("Decoded data:", decodedParcours) } success.stopAccessingSecurityScopedResource() } catch { print("Error opening file: \(error)") }
额外说明
如果你希望导出的JSON直接是TestData的扁平结构,可以修改ExportHandler的传输表示,直接编码testData而非整个ExportHandler:
static var transferRepresentation: some TransferRepresentation { DataRepresentation(contentType: .srtExportType) { handler in try JSONEncoder().encode(handler.testData) } importing: { data in let testData = try JSONDecoder().decode(TestData.self, from: data) return ExportHandler(testData: testData) } .suggestedFileName("File\(Date())") }
这种情况下,导入时就可以直接解码为TestData了。不过第一种方法更贴合你当前的代码结构,无需大幅修改。
内容的提问来源于stack exchange,提问作者Pete
相关产品推荐
相关产品推荐

