如何在Swift中修复“线程1:致命错误:在解包可选值时意外发现nil”

时间:2018-05-26 15:34:28

标签: swift avaudioplayer optional avaudiosession

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

  

“主题1:致命错误:在展开Optional值时意外发现nil。

我在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
        }
    }
}

2 个答案:

答案 0 :(得分:1)

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

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

检查此行

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

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

然后你强行包裹!它。如果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")

            }
        }

答案 1 :(得分:0)

在你的代码中,你强行打开一个可选的使用!如果你强行展开的话会导致这个错误,那就是零。在

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

如果audioPath为nil,这可能会导致错误,abetter这样做

//If this line errors, there is a problem with finding HomeSoundtrack.m4a in the bundle
let audioPathURL: URL =  Bundle.main.url(forResource: "HomeSoundtrack", withExtension: "m4a")!
do {
    player = try AVAudioPlayer(contentsOf:  audioPathURL)
} catch {
    print("Couldn't load HomeSoundtrack file with error: \(error)")
}

if let view = self.view as! SKView?

如果让它应该看起来像

if let view: SKView = self.view as? SKView {
    //Game stuff
}