Brian Josel
Brian Josel

Reputation: 69

Swift: NSBundle always set to nil when trying to set to filePath

I'm trying to set a filePath using NSBundle, even when explicitly declaring the filePath it returns nil

var filePath = NSBundle.mainBundle().pathForResource("song", ofType: "mp3", inDirectory: "/Users/name/iOS/project")

I want to pass the file path into AVAudioPlayer for playback, I have to be doing something wrong thats simple and obvious

Upvotes: 0

Views: 503

Answers (1)

Klaus Thul
Klaus Thul

Reputation: 685

NSBundle.mainBundle() refers to you application bundle. The application main bundle is a directory stored on user's device which contains your applications executable as well as all application resources (nib-files, images, anything you ship with the application).

To accomplish what you want to have do to do the following:

  1. Drag-and-drop the file "song.mp3" into your project in Xcode and make sure it is added to your target. This will make sure Xcode includes this file into your application bundle when you build your application.

  2. Change the code above to

    let filePath = NSBundle.mainBundle().pathForResource("song", ofType: "mp3")

When this line of code executes, it will look for song.mp3 inside of your application bundle and return its path. This path is a path on the device you run the application on, it is not the pass where you store the file on your development computer.

Hope this helps.

Upvotes: 1

Related Questions