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?
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.
Tested on: xCode 8.3.2 & Swift 3.1
First drag your file (JPG, MP3, ZIP) inside your project folder and make sure Copy items if needed is checked and project/app is selected in Add to targets
Inside relevant ViewController
let fileName = "fileName"
let fileType = "fileType"
if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType) {
print(filePath)
}
If you need to get the file URL you can use NSBundle method
if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType) {
print(fileURL)
}
Also NSBundle method pathForResource has an initializer that you can specify in which directory your files are located like:
if let filePath = Bundle.main.path(forResource: fileName, ofType: fileType, inDirectory: "filesSubDirectory") {
print(filePath)
}
And for getting file URL:
if let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileType, subdirectory: "filesSubDirectory") {
print(fileURL)
}
run time created file are stored in Document directory not in NSBundle. NSBundle stores the files like System file you put in your Xcode project while your developing
Here is the example
This code is fully tested on Swift 2.0
let file = "myFile.zip"
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
//path will be stored here
let sPath = dir.stringByAppendingPathComponent(file);
print(sPath) // printing the file path
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With