2016-07-29 47 views
-3

我對此很新,並試圖找出正確的格式來解決標題中的錯誤。我得到了:let audioPath = NSBundle.mainBundle()。pathForResource(「Pugs.m4a」,ofType:nil)!錯誤:致命錯誤:意外地發現零,同時展開一個可選值

我知道我必須錯過一些東西,只是不知道在哪裏。

進口的UIKit 進口AVFoundation

類的ViewController:UIViewController的{

@IBOutlet var playButton: UIButton! 

var playPug = 1 

var player: AVAudioPlayer! 

@IBAction func playPressed(sender: AnyObject) { 


    let audioPath = NSBundle.mainBundle().pathForResource("Pugs.m4a", ofType: nil)! 

    let url = NSURL(fileURLWithPath: audioPath) 

    do { 

     if playPug == 1 { 
      let sound = try AVAudioPlayer(contentsOfURL: url) 
      player = sound 
      sound.play() 
      playPug = 2 
      playButton.setImage(UIImage(named:"pause_Icon.png"),forState:UIControlState.Normal) 
     } else { 
      player.pause() 
      playPug = 1 
      playButton.setImage(UIImage(named:"play_Icon.png"),forState:UIControlState.Normal) 
     } 

    } catch { 
     print(error) 
    } 

} 
+2

如果你看Apple的文檔,你會看到這個方法是'init(contentsOfURL url:NSURL)',並且使用了Swift 2錯誤處理。文檔應始終是您的第一個地方。鏈接到'AVAudioPlayer'文檔:https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioPlayerClassReference/#//apple_ref/occ/instm/AVAudioPlayer/initWithContentsOfURL:error:。鏈接到Swift錯誤處理文檔:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html –

+1

謝謝,我看到了init(contentsOfURL url:NSURL)方法的例子。我仍然不確定如何改變它。我從來沒有見過「扔」前.. – Lou

+0

SO是不是一個教程的好地方。我建議你做一個關於Swift錯誤處理的教程的互聯網搜索。例如:https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch –

回答

1

你得到fatal error: unexpectedly found nil while unwrapping an Optional value的原因是因爲在這行代碼的!的:

let audioPath = NSBundle.mainBundle().pathForResource("Pugs.m4a", ofType: nil)! 

它正在崩潰,因爲你使用!迫使你nwrappathForResource(_:ofType:)返回的值,這是不安全的。如果值爲nil,則會出現unexpectedly found nil錯誤。當你知道他們不會成爲nil時,你應該只是強制拆包。


試着做這樣的事情,而不是:

選項1:

guard let audioPath = NSBundle.mainBundle().pathForResource("Pugs.m4a", ofType: nil) else { 
    // The resource does not exist, so the path is nil. 
    // Deal with the problem in here and then exit the method. 
} 

// The resource exists, so you can use the path. 

選項2:

使用另購的結合,就像這樣:

if let audioPath = NSBundle.mainBundle().pathForResource("Pugs.m4a", ofType: nil) { 

    // The resource exists, and now you have the path, so you can use it. 

    let url = NSURL(fileURLWithPath: audioPath) 

    do { 

     if playPug == 1 { 
      let sound = try AVAudioPlayer(contentsOfURL: url) 
      player = sound 
      sound.play() 
      playPug = 2 
      playButton.setImage(UIImage(named:"pause_Icon.png"),forState:UIControlState.Normal) 
     } else { 
      player.pause() 
      playPug = 1 
      playButton.setImage(UIImage(named:"play_Icon.png"),forState:UIControlState.Normal) 
     } 

    } catch { 
     print(error) 
    } 

} else { 
    // The path was nil, so deal with the problem here. 
} 
相關問題