2017-08-26 28 views
0

我已將這些.plist和.json文件保留在我的項目中。我可以從Xcode讀取.plist文件。儘管無法讀取Swift 3.0上的.json文件。我已經使用下面的代碼片段來獲取這個。但不能這樣做。是否有可能從.json文件獲取數據? 請分享您的建議。Swift 3.0 - 從XCode包中讀取.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") 
    } 
+1

檢查這個https://stackoverflow.com/questions/45882205/load-json-from-file-with-swift-3/45882685#45882685 –

+1

[Load from json from swift 3]可能的副本(https://stackoverflow.com/questions/45882205/load- json-from-file-with-swift-3) –

+0

加載'Data'不是'String'(並使用'Bundle'的URL相關API)。無論如何你需要'數據'來進行反序列化。 – vadian

回答

0

斯威夫特4解決方案

如果正確找到的文件路徑,文件編碼可能有問題ING。您應該明確提供json文件的實際編碼。

要檢查文件的編碼,打開XCode中的文件,看看文件檢查器在右側欄中:

Encoding of the file

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 
    } 
}