This question already has answers here:
What does “fatal error: unexpectedly found nil while unwrapping an Optional value” mean?
(11个答案)
去年关门了。
我正在尝试将音乐添加到我创建的游戏中。但我发现了一个错误:
“线程1:致命错误:在展开可选值时意外发现nil。
我发现另一篇关于堆栈溢出(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是一个Optional值,因此它可能包含nil值假定您写的HomeSoundtrack错误或找不到文件,那么audioPath将为零
然后强制包装它。在这行中,如果!audioPath则它将崩溃
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")

            }
        }

10-07 19:55
查看更多