错误:致命错误:在解包可选值时意外发现nil

时间:2016-07-29 17:25:01

标签: ios swift xcode

我对此很新,并试图找出正确的格式来解决标题中的错误。我上线了:让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)
    }

}

1 个答案:

答案 0 :(得分:1)

您获得fatal error: unexpectedly found nil while unwrapping an Optional value的原因是由于此代码行中的!

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

它崩溃是因为您正在使用! 强行解包 pathForResource(_: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.
}