How to access file included in app bundle in Swift?

后端 未结 7 1914
灰色年华
灰色年华 2020-11-30 05:46

I know there are a few questions pertaining to this, but they\'re in Objective-C.

How can I access a .txt file included in my app using Swift on

7条回答
  •  醉酒成梦
    2020-11-30 06:06

    Just a quick update for using this code with Swift 4:

    Bundle.main.url(forResource:"YourFile", withExtension: "FileExtension")
    

    And the following has been updated to account for writing the file out:

    var myData: Data!
    
    func checkFile() {
        if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
            let fileURL = documentsDirectory.appendingPathComponent("YourFile.extension")
            do {
                let fileExists = try fileURL.checkResourceIsReachable()
                if fileExists {
                    print("File exists")
                } else {
                    print("File does not exist, create it")
                    writeFile(fileURL: fileURL)
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    }
    
    func writeFile(fileURL: URL) {
        do {
            try myData.write(to: fileURL)
        } catch {
            print(error.localizedDescription)
        }
    }
    

    This particular example is not the most flexible, but with a little bit of work you can easily pass in your own file names, extensions and data values.

提交回复
热议问题