unexpectedly found nil while unwrapping an Optiona

2019-06-10 07:16发布

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.

1条回答
Deceive 欺骗
2楼-- · 2019-06-10 07:37

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
}
查看更多
登录 后发表回答