unexpectedly found nil while unwrapping an Optional value with AVAudioPlayer

耗尽温柔 提交于 2019-12-08 09:38: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:


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
}


来源:https://stackoverflow.com/questions/27094651/unexpectedly-found-nil-while-unwrapping-an-optional-value-with-avaudioplayer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!