2017-04-17 19 views
0

私のプロジェクトには1つのフォルダがあります。そのフォルダに複数のサブフォルダがあります。そして、すべてのサブフォルダには2つのjsonがありますfile.Jsonファイル名は、すべてのサブフォルダに共通です。次に、サブフォルダ名でjsonファイルを取得する方法は?つまり、私はサブフォルダ名を使ってjsonファイルを区別したいのです。私はSwiftで新しいです。ありがとうございます。同じ名前のJsonファイルを持つ複数のフォルダswift 3

答えて

1

(NS)Bundle help.Iためのおかげで実現していますが、コードがエラーでクラッシュし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

のオプションパラメータsubdirectory、サブフォルダに対処するための非常に便利な方法を提供します:致命的なエラーを:ファイルパスを確認してください:file /Users/mac/Desktop/practise/UnzipFilePratice/UnzipFilePratice/ViewController.swift、line 25 –

+0

もちろん、すべてのリテラルパスを実際のパスに変更する必要がありますrバンドル。また、Xcodeの黄色のディレクトリは、ファイルシステムの実際のディレクトリではないと考えてください。これらのディレクトリは青色でなければなりません。 – vadian

+0

私のフォルダ名は英語で、サブフォルダ名は開いています..------------------------------------- ----- let 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) 
       } 

}

関連する問題