How to access file included in app bundle in Swift?

atirit picture atirit · Jun 2, 2016 · Viewed 52.4k times · Source

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 an actual iPhone? I want to be able to read and write from it. Here are my project files if you want to take a look. I'm happy to add details if necessary.

Answer

Karim H picture Karim H · Jun 2, 2016

Simply by searching in the app bundle for the resource

var filePath = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")

However you can't write to it because it is in the app resources directory and you have to create it in the document directory to write to it

var documentsDirectory: NSURL?
var fileURL: NSURL?

documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last!
fileURL = documentsDirectory!.URLByAppendingPathComponent("file.txt")

if (fileURL!.checkResourceIsReachableAndReturnError(nil)) {
    print("file exist")
}else{
    print("file doesnt exist")
    NSData().writeToURL(fileURL!,atomically:true)
}

now you can access it from fileURL

EDIT - 28 August 2018

This is how to do it in Swift 4.2

var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")

To create it in the document directory

if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
   let fileURL = documentsDirectory.appendingPathComponent("file.txt")
   do {
       if try fileURL.checkResourceIsReachable() {
           print("file exist")
       } else {
           print("file doesnt exist")
           do {
            try Data().write(to: fileURL)
           } catch {
               print("an error happened while creating the file")
           }
       }
   } catch {
       print("an error happened while checking for the file")
   }
}