【问题标题】:What can I do to fix this error?我能做些什么来解决这个错误?
【发布时间】:2016-03-25 16:06:54
【问题描述】:

每次尝试运行时都会出现错误提示

致命错误:在展开可选值 (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
        }
    }
}

【问题讨论】:

  • 您的 nil 很可能来自分配给 audioPath 时 pathForResource 的展开。您是否仔细检查了 audioPath 的路径。您的 mp3 是否包含在您的项目中?
  • 是的,包括 Mp3。它只是找不到路径

标签: swift


【解决方案1】:

此错误几乎总是由强制展开对象引起的,即“!”操作符。对于您的代码,很可能是这一行:

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 */
}

【讨论】:

    【解决方案2】:

    您正在强制解开代码行中的可选项:

    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
    }
    

    希望对你有所帮助。

    【讨论】:

    • 由于某种原因,您提供的代码可以正常工作,但是当我运行它时,我无法在模拟器中播放音乐。模拟器有自己的声音还是只有 Mac 本身。
    • @D.watts 我的回答解决了您的问题,以获取有关您的其他错误的更多信息我推荐您stackoverflow.com/questions/24962822/…stackoverflow.com/questions/30986446/…
    • 好的,感谢您的帮助。在您提供的代码中。它打印了找不到路径,我猜这表明它找不到路径。这是否意味着我使用的来源不好?
    • 不客气 :)。是的,可能是这样,您需要小心放置文件的位置并注意名称。如果答案解决了您的问题,请接受它可以帮助其他人
    【解决方案3】:

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

    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")
          }
    

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多