How can I fix “Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value” in Swift [duplicate]

ぐ巨炮叔叔 提交于 2019-12-10 12:00:44

问题


I am trying to add music to a game I created. But I am getting the error:

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

I found another post on Stack Overflow (What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?), but I do not understand how this applies to my code.

This is my code:

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

回答1:


Optional value is value that may be contain nil if you want to get its value you have to wrapping it

but use safe wrapping not force wrapping !

check this line

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

audioPath is An Optional so it may contain nil value assume that you write HomeSoundtrack Wrong or file not found then audioPath will be nil

then you force wrapping ! it . in this line if audioPath is nil then it will crash

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

can be done safe

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

            }
        }



回答2:


In your code you are force unwrapping an optional using ! which can cause this error if what you are force unwrapping happens to be nil. In

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

this could cause the error if the audioPath is nil, abetter to do it would be

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

or in

if let view = self.view as! SKView?

this if let should probably look like

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


来源:https://stackoverflow.com/questions/50544358/how-can-i-fix-thread-1-fatal-error-unexpectedly-found-nil-while-unwrapping-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!