-4

I'm trying out some basic stuff like playing audio.

Right in the beginning when I ran the project I got an error, the error doesn't show up in the view controller but it pops up right away when I run the project.

fatal error: unexpectedly found nil while unwrapping an Optional value

My code:

var buttonAudioURL = try? NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Sound", ofType: "m4a")!)
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • 3
    Have you read the documentation? It's all in the error. You used `!` on a `nil` value and that's not allowed in Swift (see the NSBundle part). – Arc676 Oct 27 '15 at 11:11
  • Convention on SO is if you found an answer useful, upvote it; if you found an answer that helped you solve your problem, mark it as "accepted" (checkmark button under the votes button). You haven't done this ever - not fair. :) – Eric Aya Nov 02 '15 at 14:42

1 Answers1

2

With NSBundle.mainBundle().pathForResource("Sound", ofType: "m4a")! you are forcing the unwrapping of the Optional returned by NSBundle (note the ! at the end).

So if this resource "Sound.m4a" is unavailable, as it seems to be the case, the app will crash.

You need two things: make sure that the resource is in the bundle, and use safe unwrapping and error handling instead of force-unwrapping.

I strongly suggest you read the nice docs Apple has made available for us, all of this is explained in detail.

Also note that NSURL doesn't throw so you don't have to use try with it.

Update

Here's an example of what I'm talking about:

if let soundResourceURL = NSBundle.mainBundle().pathForResource("Sound", ofType: "m4a") {
    let buttonAudioURL = NSURL(fileURLWithPath: soundResourceURL)
    // use buttonAudioURL here
} else {
    print("Unable to find Sound.m4a")
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253