swift - 使用 AVAudioPlayer 解包 Optional 值时意外发现 nil

标签 swift ios-simulator avaudioplayer nserror ipad-mini

因此这段代码在 iOS 模拟器上运行良好,但在我的 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?

我在最后一行收到错误“unexpectedly found nil while unwrapping an Optional value”。

最佳答案

看起来 AVAudioPlayer 还没有被审计。它返回一个隐式解包的可选值,它可以是 nil,显然 在你的 iPad 上。 (可能是因为您的 iPad 不知道 /Users/Dan/Documents/... 在哪里,因为它在您的计算机上。)

你想在一个可选值中捕获播放器,这样你就可以在使用它之前测试 nil:

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
}

关于swift - 使用 AVAudioPlayer 解包 Optional 值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27094651/

相关文章:

IOS 查询当前音频音量

ios - 无法在模拟器中运行应用程序

ios - 全屏 js iOS Safari

iPhone 6.1 模拟器

ios - 动画队列使用 Facebook POP 和 Swift 将一系列 UILabels 滑出 View

iphone - 使用 AVAudioPlayer 播放多个音频文件

ios - 音频不在后台模式下播放

swift - iOS 9 中的 requestLocation() 多次调用 didUpdateLocation 委托(delegate)

ios - UIPageViewController 中的动画

ios - 游戏中心不保存分数