Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") returning null

Tags:

swift

NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg")

The above code is returning null.

In order to check if the file exists or not, I used below code:

let fileManager = NSFileManager.defaultManager()

if fileManager.fileExistsAtPath(savepath) {
  println("exist")
}

The above code returns that file exists in directory.

So I don't understand why the first code is returning null

like image 658
Sukhdeep Singh Kalra Avatar asked Feb 26 '15 17:02

Sukhdeep Singh Kalra


5 Answers

I had this issue too. My fix was:

  • Selecting the file in project navigator
  • Open the 'File Inspector' (on the right hand side pane)
  • Checking the app target in the Target Membership
like image 187
Hayden Malcomson Avatar answered Oct 19 '22 02:10

Hayden Malcomson


Your problem is that NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") returns an optional NSURL. You need to use if let to unwrap it and extract your file path from the returned url as follow:

if let resourceUrl = NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") {
    if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) {
        print("file found")
    }
}
like image 24
Leo Dabus Avatar answered Oct 19 '22 01:10

Leo Dabus


Swift 3.x

if let resourceUrl = Bundle.main.url(forResource: "bach1", withExtension: "jpg") {
    if FileManager.default.fileExists(atPath: resourceUrl.path) {
        print("file found")
    }
}
like image 32
Rajan Maheshwari Avatar answered Oct 19 '22 02:10

Rajan Maheshwari


I found that you have to actually go into Build Phases -> Copy Bundle Resources and manually add your item sometimes to the bundle. In my case it was a video file that didn't get added to the bundle correctly on its own.

like image 34
Unome Avatar answered Oct 19 '22 02:10

Unome


NSBundle.URLForResource only returns files that are bundled in your application at build/compile time, like when you drag a file into your Xcode project and add it to your app target. You can typically use this when your app comes preloaded with resources you need, like images, movies, databases, and other files.

It seems like savepath is a path your application wrote to while running (maybe into your app's Documents directory?). Because of this, the file is outside of the bundle and you will need to store that path/URL somewhere (or build it up again) if you need to reference the file in the future.

like image 30
Warota Avatar answered Oct 19 '22 02:10

Warota