2017-04-08 83 views
0

所以,當我使用這個功能設置AVAudioPlayer:swift_unexpectedError嘗試播放音頻

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) 

有時它崩潰在第一行上,有時在第二。我該如何解決?什麼可能導致這些崩潰?

+0

你不應該使用'試試!'如果你在一個'do'塊包裝你的代碼。只需使用'try'。 – JAL

+0

是的,這是問題的一半,但我也想知道是什麼導致了這些崩潰。 – TimSim

回答

1

其實,我不知道什麼是導致飛機失事的原因(ES)的原因想法,但要防止它們,則應更換try!trydo塊讓catch能夠處理任何預期的錯誤。目前,do catch只處理try audioPlayer = AVAudioPlayer,try! 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?