简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM