尝试播放音频时swift_unexpectedError

时间:2017-04-08 23:41:25

标签: ios swift error-handling try-catch

所以,我使用此功能设置AVAudioPlayer:

func setupAudioPlayerWithFile(file: String) -> AVAudioPlayer? {
    var audioPlayer: AVAudioPlayer?
    if let sound = NSDataAsset(name: file) {
        do {
            try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
            try! AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = AVAudioPlayer(data: sound.data, fileTypeHint: AVFileTypeWAVE)
        } catch {
            print("error initializing AVAudioPlayer")
        }
    }
    return audioPlayer
}

但是我收到了数百起用户报告的崩溃事件。我无法复制任何崩溃。

崩溃发生在这两行:

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try! AVAudioSession.sharedInstance().setActive(true)

有时它会在第一行崩溃,有时会在第二行崩溃。我该如何解决?什么可能导致这些崩溃?

1 个答案:

答案 0 :(得分:1)

实际上,我不知道导致崩溃的原因是什么,但为了防止它们,您应该将try!替换为try do阻止让catch能够处理任何预期的错误。目前,do catch仅处理try audioPlayer = AVAudioPlayertry! AVAudioSessiontry! AVAudioSession 应该导致崩溃如果发生错误。

为了更清楚,请考虑以下示例:

enum FirstError: Error {
    case FirstError
}

func throwFirstErrorFunction() throws {
    throw FirstError.FirstError
}

enum SecondError: Error {
    case SecondError
}

func throwSecondErrorFunction() throws {
    throw SecondError.SecondError
}

案例#1:

try! throwFirstErrorFunction() // crash

应用程序应该崩溃。

案例#2:

do {
    try throwFirstErrorFunction()
    //try throwSecondErrorFunction()
} catch (let error) {
    print(error) // FirstError
}

应打印FirstError

案例#3(你面对的是什么):

do {
    try! throwFirstErrorFunction() // crash
    try throwSecondErrorFunction()
} catch (let error) {
    print(error)
}

应用程序应该崩溃,为什么?因为do catch仅处理try而不处理try!

案例#4(解决方案):

do {
    try throwSecondErrorFunction()
    try throwFirstErrorFunction()
} catch (let error) {
    print(error) // SecondError
}

应打印SecondError。请注意,首先捕获的错误将由catch块处理 - 并且应跳过其他try

同时

我建议您查看try, try! & try? what’s the difference, and when to use each?