我正在尝试使用此代码从文件加载 json 字符串。
if let filepath = Bundle.main.path(forResource: "data", ofType: "json") {
do {
let contents = try String(contentsOfFile: filepath)
print(contents)
} catch {
// contents could not be loaded
print("could not be loaded")
}
} else {
}
但我收到“无法加载”消息。代码有错吗?还是我应该将文件放在特定文件夹中?目前我将它放在一个名为 models 的文件夹中。
编辑: 我检查了错误内容,json 文件的位置没有问题,当我尝试将其转换为字符串时出现问题。它告诉我编码不同......
Error Domain=NSCocoaErrorDomain Code=264 "Die Datei „data.json“ konnte nicht geöffnet werden, da die Textcodierung des Inhalts nicht bestimmt werden kann."
最佳答案
首先确保你已经标记了copy item if needed
复选标记,并且你的目标在你添加你的.json文件时也被标记了,之后你的主要问题是你加载文件的方式,您需要使用 Data
而不是 String
使用此方法加载您的 json 并在回调中获取结果
func loadJSON(finishedClosure:@escaping ((_ jsonObject:[String:AnyObject]?,_ error: NSError?) ->Void))
{
DispatchQueue.global().async {
guard let path = Bundle.main.path(forResource: "yourJSON", ofType: "json") else{
DispatchQueue.main.async {
finishedClosure(nil, NSError(domain: "JSON file don't founded", code: 998, userInfo: nil))
}
return
}
//Load file data part
guard let jsonData = (try? Data(contentsOf: URL(fileURLWithPath: path))) else{
DispatchQueue.main.async {
finishedClosure(nil, NSError(domain: "can convert to data", code: 999, userInfo: nil))
}
return
}
do {
if let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:AnyObject]
{
DispatchQueue.main.async {
finishedClosure(jsonObject,nil)
}
}
} catch let error as NSError {
print(error)
DispatchQueue.main.async {
finishedClosure(nil,error)
}
}
}
}
关于ios - 使用 swift 3 从文件加载 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45882205/