我该怎么做才能解决这个错误?

时间:2016-03-25 16:06:55

标签: swift

每次尝试运行陈述

时都会出错
  

致命错误:在展开Optional值(lldb)时意外发现nil。

有人可以解释原因吗?继承人的代码

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player: AVAudioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3")!

        do {
           try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
           player.play()
        } catch {
            // Process error here
        }
    }
}

3 个答案:

答案 0 :(得分:0)

此错误几乎总是由强制展开对象(即"!"运算符)引起的。对于你的代码,它很可能是这一行:

let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3")!

有可能无法找到该文件。为了安全起见并处理此错误情况,请使用:

if let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3") {
    /* do what you need to with the path*/
 }
else{
    /* handle error case */
}

答案 1 :(得分:0)

您在代码行中强制展开可选项:

let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3")!

如果资源不存在,此文件可以返回一个可选项,避免强制解包可选,而是使用可选绑定或guard语句,如下所示。它总是建议不要强制解包一个可选项,因为你告诉编译器你知道它总是与nil不同,如果它发生了,你会得到一个运行时错误。

if let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3") {
   do {
       try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
       player.play()
    } catch {
        // Process error here
    }
}

guard

guard let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3") else { return }

do {
     try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
     player.play()
} catch {
   // Process error here
}

我希望这对你有所帮助。

答案 2 :(得分:0)

可能是找不到音频文件。试试这个

if let audioPath = NSBundle.mainBundle().pathForResource("Belly - Might Not", ofType: "mp3"){

        do {
          try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))
          player.play()
        } catch {
          // Process error here
        }

      }else{
        print("path not found")
      }