简体   繁体   中英

local file path won't import

I am trying to import the content of a .txt file to a string in my Xcode 9 project using Swift 4. When I use the full path name it imports successfully, current code:

let filePath = URL(fileURLWithPath: "/Users/main/Documents/ClaasPDI/PDIapp/PDIapp/holdMachines.txt")

do
{
    machineString = try String(contentsOf: filePath)

}
catch
{
    print("MACHINE INFORMATION DID NOT IMPORT")
}

I want to be able to import the data from the local path so it can be run on other computers besides mine. My swift files and holdMachines.txt are in the same folder PDIapp but when I change the code to:

let filePath = URL(fileURLWithPath: "holdMachines.txt")

it now crashes my app and says it could not access the file.

I also tried it with a / infront of the file name (below) but that also failed.

let filePath = URL(fileURLWithPath: "/holdMachines.txt")

How can I change my code to access the file through a local file path?

Put the text file in your Xcode project and use the following code to read it into a string:

let txtFile = Bundle.main.path(forResource: "holdMachines", ofType: "txt")
do {
        let contents = try? String(contentsOfFile: txtFile!, encoding: .utf8)
} catch let err {
        print(err.localizedDescription)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM