【发布时间】:2018-08-14 19:51:06
【问题描述】:
Swift 4.0 iOS 11.2.x
我在这里创建了一个名为 products 的 Codable stuct,并使用此方法将其保存到文件中。
func saveImage() {
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let file2ShareURL = documentsDirectoryURL.appendingPathComponent("config.n2kHunt")
var json: Any?
let encodedData = try? JSONEncoder().encode(products)
if let data = encodedData {
json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let json = json {
do {
try String(describing: json).write(to: file2ShareURL, atomically: true, encoding: .utf8)
} catch {
print("unable to write")
}
}
}
}
它有效,假设我输入了两条记录,我将其存档。 [不是 json,而是随便什么]。
(
{
identity = "blah-1";
major = 245;
minor = 654;
url = "https://web1";
uuid = f54321;
},
{
identity = "blah-2";
major = 543;
minor = 654;
url = "https://web2";
uuid = f6789;
}
)
我将文件空投到第二台 iOS 设备,并尝试在 appDelegate 中使用此过程对其进行解码。
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
do {
let string2D = try? String(contentsOf: url)
let jsonData = try? JSONSerialization.data(withJSONObject: string2D)
do {
products = try JSONDecoder().decode([BeaconDB].self, from: jsonData!)
} catch let jsonErr {
print("unable to read \(jsonErr)")
}
} catch {
print("application error")
}
}
我遇到了母亲崩溃,并带有此错误消息...
2018-03-06 21:20:29.248774+0100 blah[2014:740956] * 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'* +[NSJSONSerialization dataWithJSONObject:options:错误:]:JSON 写入中的顶级类型无效'
我做错了什么;如何将 json 写入文件以便我可以读回它!具有讽刺意味的是,几天前我使这段代码与 plist 一起工作,我讨厌 json。
【问题讨论】:
标签: ios json decode swift4 encode