Get file path from NSBundle in Swift

matt picture matt · Dec 17, 2015 · Viewed 9.4k times · Source

I have a file stored in:

/var/mobile/Containers/Data/Application/083EA15E7/Documents/myFile.zip

It got there after I downloaded it from a server.

If I know the file name is myFile.zip, how can I find it with NSBundle?

Like this:

if let URL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "zip") {
    // do stuff
}

currently this returns false, not sure how I can specify the whole path. Any ideas?

Answer

Ahmad picture Ahmad · Dec 17, 2015

This item is not in your bundle, an item in your bundle is something that you add before compiling, such as assets, fonts etc.

iOS provides each app with a sandbox. In that sandbox, the Documents folder exists. To access files from the Documents folder try this:

let documentsURL = NSURL(
  fileURLWithPath: NSSearchPathForDirectoriesInDomains(
    .DocumentDirectory, .UserDomainMask, true).first!,
  isDirectory: true
)

To get the file, you will need to get its path and append it to the documents path like so.

let URLToMyFile = documentsURL.URLByAppendingPathComponent("MyFile.zip")

To get the path as a string you can access the path property of the URL.

print(URLToMyPath.path!)

That will print out the path of your downloaded resource.