I am using Xcode 7.0.1 Swift 2 iOS 9. While playing sound I get this error:
"fatal error: unexpectedly found nil while unwrapping an Optional value"
and this is my code:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
playSound(enumerator![indexPath.item] )
}
func playSound(soundName: String)
{
let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!)
do{
let audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
NSBundle pathForResource(name: String?, ofType ext: String?) -> String?
returns an optional, and you are force unwrapping. Either your path is wrong or your resource is not there.
And looking at the image sound name has .m4a
extension. If you want to provide extension yourself, you can skip ofType
and pass nil
or separate the extension from the name of the resource and send both parameters.
To be safe, you should always check for optionals when you are not sure if it has value or not
let pathComponents = soundName.componentsSeparatedByString(".")
if let filePath = NSBundle.mainBundle().pathForResource(pathComponents[0], ofType: pathComponents[1]) {
let coinSound = NSURL(fileURLWithPath: filePath)
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments