path = Bundle.main.path(forResource: "Owl.jpg", ofType: "jpg")
returns nil, however, using NSHomeDirectory() I'm able to verify that is under Documents/ folder.
path = Bundle.main.path(forResource: "Owl.jpg", ofType: "jpg")
returns nil, however, using NSHomeDirectory() I'm able to verify that is under Documents/ folder.
First, separate name and extension:
Bundle.main.path(forResource: "Owl", ofType: "jpg")
Second, separate (mentally) your bundle and the Documents folder. They are two completely different things. If this file is the Documents folder, it absolutely is not in your main bundle! You probably want something like this:
let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let myurl = docsurl.appendingPathComponent("Owl.jpg")
Third, if Owl is an image asset in the asset catalog, then say
let im = UIImage(named:"Owl") // or whatever its name is
.main) bundle (Bundle). (At zero depth.) One point of the asset catalog is that there is no need for paths; you just use a thing's name, because the runtime knows where the asset catalog is and how to read things by name within it. If you wanted this thing to be in your main bundle, then you shouldn't have put it in the asset catalog. Those are different places. I believe I've said this before. Perhaps more than once.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)
}