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