2017-04-17 82 views
0

我很難獲取Json文件。在我的項目中有一個文件夾,在該文件夾中有多個子文件夾。並且在每個子文件夾中有兩個json file.Json文件名是常見的每個子文件夾中。那麼我如何獲取帶有子文件夾名稱的json文件?這意味着我想通過子文件夾名稱來區分json文件。我是Swift中的新成員。謝謝。具有相同名稱的Json文件的多個文件夾swift 3

回答

1

(NS)Bundle提供了一個非常方便的方式來解決的子文件夾,可選參數的url(forResource: withExtension:)

if let jsonFileURL = Bundle.main.url(forResource: "jsonFile", 
        withExtension: "json", 
         subdirectory: "Subfolder1/SubFolder2") { 

    let json = try! String(contentsOf: jsonFileURL, encoding: .utf8) 
    print(json) 

} else { fatalError("Check the file paths") } 
+0

感謝help.I subdirectory已經實現,但代碼與錯誤而崩潰:致命錯誤:檢查文件路徑:file /Users/mac/Desktop/practise/UnzipFilePratice/UnzipFilePratice/ViewController.swift,第25行 –

+0

當然,您必須將所有文字路徑更改爲您的實際文字路徑r捆綁。還要考慮Xcode中的黃色目錄不是文件系統中的真實目錄。這些目錄必須是藍色的。 – vadian

+0

我的文件夾名稱是英文和子文件夾名稱正在打開.. .. .. .. .. --------------------------------------- ----- 如果讓jsonFileURL = Bundle.main.url(forResource:「content」,withExtension:「txt」,子目錄:「English/opening」) –

2

通過在文檔路徑中提供實際的文件夾名稱,您可以從不同的文件夾獲取該文件。

確保您的文件已添加到資源中。

if let docsPath = Bundle.main.resourcePath! + "/Resources/subfolder" { 
       let fileManager = FileManager.default 

       do { 
        let docsArray = try fileManager.contentsOfDirectory(atPath: docsPath) 
        //get the required json file from the documents array 

       } catch { 
        print(error) 
       } 

}

相關問題