使用AVAudioPlayer解开Optional值时意外发现n

使用AVAudioPlayer解开Optional值时意外发现n

本文介绍了使用AVAudioPlayer解开Optional值时意外发现nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,此代码在iOS模拟器上运行正常,但在我的iPad Mini上运行不正常

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?

我在最后一行收到错误消息在解开可选值时意外发现nil".

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

推荐答案

AVAudioPlayer似乎尚未经过审核.它返回一个隐式解包的可选内容,可以为nil,显然在iPad上为 is . (可能是因为您的iPad不知道/Users/Dan/Documents/...的位置,因为它在您的计算机上.)

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.)

您想以一个可选值捕获播放器,以便在使用nil之前对其进行测试:

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
}

这篇关于使用AVAudioPlayer解开Optional值时意外发现nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 03:55