Search code examples
swiftios-simulatoravaudioplayernserroripad-mini

unexpectedly found nil while unwrapping an Optional value with AVAudioPlayer


So this code runs fine on the iOS Simulators, but not on my iPad Mini

    var sound = NSURL(fileURLWithPath:"/Users/Dan/Documents/XCode Code/Colors- Tabbed?/Colors- Tabbed?/Sweg.aiff")
    var audioPlayer = AVAudioPlayer()
    audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: &error)
    var error: NSError?

I get the error "unexpectedly found nil while unwrapping an Optional value" on the last line.


Solution

  • It looks like AVAudioPlayer hasn't been audited yet. It returns an implicitly unwrapped optional, which can be nil, and apparently is on your iPad. (Likely because your iPad doesn't know where /Users/Dan/Documents/... is, since that's on your computer.)

    You want to capture the player in an optional value so you can test for nil before you use it:

    var sound = NSURL(fileURLWithPath:"/Users/Dan/Documents/XCode Code/Colors- Tabbed?/Colors- Tabbed?/Sweg.aiff")
    var error: NSError?
    var audioPlayer: AVAudioPlayer? = AVAudioPlayer(contentsOfURL: sound, error: &error)
    
    if let audioPlayer = audioPlayer {
        // do things with the audioPlayer
    }