user2971617 user2971617 - 16 days ago 10
Swift Question

Swift3 : unexpectedly found nil while unwrapping an Optional value

I ve just upgrade from Swift 2 to Swift 3, and i m facing a new challenge...

I have a player which run perfectly before, but now i have this following issue : "unexpectedly found nil while unwrapping an Optional value"

Here is my code :

print(audioselectionne)

let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: audioselectionne as String, ofType: "mp3")!)


I ve got : Optional("tiesto") and the crash...

I really dont understand where is the issue...

Thanks for the help.

Answer

I think the Bundle.main.path method returns an optional String. When that’s nil (because the resource was not found), force-unwrapping it causes your error. If you want to handle it correctly, you have to check for the nil:

guard let path = Bundle.main.path(…) else {
    // resource not found, handle error
}

// now `path` is guaranteed to be non-nil
let alertSound = URL(fileURLWithPath: path)