0
votes

For some reason, Xcode is throwing an error when my code is run, saying

"Fatal error: unexpectedly found nil while unwrapping an Optional value".

The only problem is I am not unwrapping anything in this line of code that it says caused the error. AVAudioPlayer is a class, not a variable and so cannot be an optional.

Code:

import UIKit
import AVFoundation
class FirstViewController: UIViewController {
    var label = AVAudioPlayer()
    var someSounds = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("EvilLaugh", ofType: "mp3")!)
    @IBAction func activation(sender: UIButton) {
        label = AVAudioPlayer(contentsOfURL: someSounds, error: nil) // This is where Xcode is throwing an error
        label.prepareToPlay()
        label.play()

Edit: The first possible duplicate question I did check prior to asking this question which did not solve my problem, but the second I did not find prior. Please feel free to remove this question.

2
someSounds is probably returning nil because it cannot find the pathForResourcle for EvilLaughYarneo

2 Answers

2
votes

According to NSURL Class Reference the fileURLWithPath: is returning an optional value. And when you initialise the AVAudioPlayer the url argument is first unwrapped, in your case the url is nil and the application crashes.

For fixing this issue, you need to change your IBAction code like:

@IBAction func activation(sender: UIButton)
{
    if let someSounds = someSounds
    {
        label = AVAudioPlayer(contentsOfURL: someSounds, error: nil) // This is where Xcode is throwing an error
        label.prepareToPlay()
        label.play()
    }
}
1
votes

Actually when initalizing the somesounds variable you are unwrapping an optional :

var someSounds = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("EvilLaugh", ofType: "mp3")!)

So the someSounds variable might be nil at runtime.

Then when using the AvaudioPlayer initializer you're passing in this nil value, hence the RuntimeError :

 AVAudioPlayer(contentsOfURL: someSounds, error: nil)