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?)的文章,但我不明白这是如何应用于我的代码的。
这是我的代码:
audioPath是一个
然后强制包装它。在这行中,如果
可以做到安全
(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")
}
}