写文主要为了记录读取json文件失败的问题及解决方案
问题特征:<The file couldn’t be opened>
读取Json文件
guard let path = Bundle.main.path(forResource: "xx", ofType: "json") else {
return
}
do {
let url = URL(fileURLWithPath: path)
let data = try Data(contentsOf: url)
} catch let e as Error? {
print("\(e)")
}
// let doecode = try? JSONDecoder().decode([MODEL].self, from: data)
读取失败: The file “xxx.json” couldn’t be opened
解决方案:注意文件URL的初始化方法
正确:let url = URL(fileURLWithPath: path)
错误:let url = URL(string: path)
完整错误信息:
** nil host used in call to allowsSpecificHTTPSCertificateForHost**
** nil host used in call to allowsAnyHTTPSCertificateForHost:**
** NSURLConnection finished with error - code -1002**
** CFURLCopyResourcePropertyForKey failed because it was passed a URL which has no scheme**
**Optional(Error Domain=NSCocoaErrorDomain Code=256 "The file “xxx.json” couldn’t be opened." UserInfo={NSURL=/xxxx.json})**