0

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.

  • possible duplicate of [Fatal error: unexpectedly found nil while unwrapping an Optional values](http://stackoverflow.com/questions/24643522/fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-values) – Anbu.Karthik Sep 02 '15 at 06:15
  • someSounds is probably returning nil because it cannot find the pathForResourcle for EvilLaugh – Yarneo Sep 02 '15 at 06:19
  • possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – jtbandes Sep 02 '15 at 06:32

2 Answers2

2

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()
    }
}
Midhun MP
  • 90,682
  • 30
  • 147
  • 191
1

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)
EI Captain v2.0
  • 21,360
  • 10
  • 76
  • 103
afraisse
  • 2,714
  • 1
  • 10
  • 12