-1

I've found a bug on my app but only when the app runs on a device, if the app runs using the simulator no error is generated.

I've located the error down to the background music script, the output error is fatal error: unexpectedly found nil while unwrapping an Optional value. I've looked at similar questions here but found no remedy.

Can anyone help fix my code?

    var bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "aif")!
    backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil) //error here!!!
    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()

Please let me know if you need more code.

Thank you.

Rich Townsend
  • 571
  • 1
  • 5
  • 21

2 Answers2

1

Double check that the following is not nil on the device:

NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "aif")

Force unwrapping the failable init of NSURL is asking for a crash. You should bind the value with:

if let bgMusicURL = NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "aif") {
    backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil)
    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()
}
Mr Beardsley
  • 3,743
  • 22
  • 28
  • But you are not explaining why it would be nil on the device and not on the simulator. – matt Sep 02 '15 at 22:35
1

Is your bgMusic.aif file added to your target ?

If not it may play ok on the simulator, but not on the device

Glenn
  • 2,808
  • 2
  • 24
  • 30