swift - 如何在 Swift 中修复 "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

标签 swift avaudioplayer option-type avaudiosession

<分区>

我正在尝试将音乐添加到我创建的游戏中。但我收到错误:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

我在 Stack Overflow (What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?) 上找到了另一篇文章,但我不明白这如何适用于我的代码。

这是我的代码:

import UIKit
import SpriteKit
import GameplayKit
import AVFoundation

class GameViewController: UIViewController {
    var player:AVAudioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            let audioPath = Bundle.main.path(forResource: "HomeSoundtrack", ofType: "m4a")
            try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
        }
        catch {
        }

        let session = AVAudioSession.sharedInstance()

        do {
            try session.setCategory(AVAudioSessionCategoryPlayback)
        }
        catch {
        }

        player.play()

        if let view = self.view as! SKView? {
            // Load the SKScene from 'GameScene.sks'
            if let scene = SKScene(fileNamed: "GameScene") {
                // Set the scale mode to scale to fit the window
                scene.scaleMode = .aspectFill

                // Present the scene
                view.presentScene(scene)
            }

            view.ignoresSiblingOrder = true

            view.showsFPS = false
            view.showsNodeCount = false
        }
    }

    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }
}

最佳答案

可选值是可以包含nil的值,如果你想得到它的值你必须包装它

但使用安全包装而不是强制包装 !

检查这一行

let audioPath = Bundle.main.path(forResource: "HomeSoundtrack", ofType: "m4a")

audioPath 是一个可选的,因此它可能包含nil 值假设您编写的HomeSoundtrack 错误或找不到文件,那么audioPath 将为nil

然后你强制包装 ! 它。在这一行中,如果 audioPathnil 那么它将崩溃

try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)

可以安全地完成

  let audioPathURL =  Bundle.main.url(forResource: "HomeSoundtrack", withExtension: "m4a")
        {
            do {
                player = try AVAudioPlayer(contentsOf:  audioPathURL)
            }  catch {
                print("Couldn't load HomeSoundtrack file")

            }
        }

关于swift - 如何在 Swift 中修复 "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50544358/

相关文章:

swift - 使用外部源动态创建 NSPopUpButton (项目数量)

swift - 如何在 Swift 中构建通用类型协议(protocol)一致性?

ios - 如何在ios中为多个 View 创建相同的计时器?

java - 用 Java 8 Optional 替换重复的 get 语句

xcode - 在 Xcode 断点显示时间

苹果手机 : getting error of "_AudioSessionSetProperty" while playing recording

swift - 在不同的 ViewController 中停止 AudioPlayer

ios - 如何获取在NsData中下载的音频文件?

swift - 可选绑定(bind)的参与者的姓名是什么?

swift - pickerView 在展开 Optional 时意外发现 nil