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写入文件以便我可以将其读回!!具有讽刺意味的是,几天前我用这个代码使用了这个代码,我讨厌json。
答案 0 :(得分:2)
为什么要将结构编码为JSON,然后将JSON反序列化为Swift数组并将集合类型字符串表示形式(!)保存到磁盘?反过来不能工作,这会导致错误。
这更容易:
func saveImage() {
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let file2ShareURL = documentsDirectoryURL.appendingPathComponent("config.n2kHunt")
do {
let encodedData = try JSONEncoder().encode(products)
try encodedData.write(to: file2ShareURL)
} catch {
print("unable to write", error)
}
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
do {
let jsonData = try Data(contentsOf: url)
products = try JSONDecoder().decode([BeaconDB].self, from: jsonData)
} catch {
print("unable to read", error)
}
}
注意:
catch
子句中打印无意义的文字字符串,至少打印实际的error
。try?
块中写do - catch
。将问号try
写入执行以捕获错误。