我在我的项目中保留了这些 .plist 和 .json 文件。我可以从 Xcode 读取 .plist 文件。虽然无法在 Swift 3.0 上读取 .json 文件。我使用下面的代码片段来获取它。但不能那样做。是否可以从 .json 文件中获取数据? 请分享您的建议。
可以获取 PLIST 文件
let plistFile = Bundle.main.path(forResource: "content", ofType: "plist")
let dictPlist = NSDictionary(contentsOfFile: plistFile!)
print(dictPlist ?? "")
无法获取 JSON 文件
if let filepath = Bundle.main.path(forResource: "fruits", ofType: "json") {
do {
let contents = try String(contentsOfFile: filepath)
print(contents)
} catch {
print("Fetched")
}
} else {
print("not found")
}
最佳答案
Swift 4 解决方案
如果正确找到文件路径,则可能是文件编码有问题。您应该明确提供 json 文件的实际编码。
要检查文件的编码,请在 XCode 中打开文件并查看右侧栏中的文件检查器:
if let filePath = Bundle.main.path(forResource: "data", ofType: "json"),
let data = NSData(contentsOfFile: filePath) {
do {
// here you have your json parsed as string:
let jsonString = try? String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
// but it is better to use the type data instead:
let jsonData = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments)
}
catch {
//Handle error
}
}
关于ios - Swift 3.0 - 从 XCode 包中读取 .JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892194/