简体   繁体   中英

Read file in Xcode project with Swift

I made a method to read a file from the temporary folder. I use the following lines to get the document's path:

path = NSTemporaryDirectory().stringByAppendingPathComponent(folder)
path = path.stringByAppendingPathComponent(fileName + "." + fileType)

And it works great. My question is: how do I get the path for a file located in the main folders of the Xcode project? They are two text files that I drag and drop from a folder to the Xcode project. I selected the option "copy files if needed" when dropping the files. Thanks!

What you are looking for is app's main bundle. You get a path of a file in it like this:

if let path = NSBundle.mainBundle().pathForResource(fileName, ofType:fileType) {
    // use path
}

Keep in mind this folder is read-only so you will need to copy the files to temp or documents folders if you want to make changes.

Update the Swift 3.1 - Thanks @Filip Radelic

if let path = Bundle.main.path(forResource: fileName, ofType: fileType) {
    // use path
    print(path)
}

You would use NSBundle to get your main bundle, then pathForResource(_ name: String?, ofType extension: String?) -> String? .

Swift 4

  if let path = Bundle.main.path(forResource: "imagename.png", ofType: nil) {
           print("[check] FILE AVAILABLE \(path)")
        }

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