-2

enter image description here

guard let urlString = urlString else {
            print("urlstring is nil")
            return
        }

        player = try AVAudioPlayer(contentsOf: (URL(string: urlString))!)

        guard let player = player else {
            print("player is nil")
            return
        }
        player.volume = 0.5

        player.play()
    }
    catch {
        print("error occurred")
    }

ERROR CODE:Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    `urlString` is not a valid URL or the API is wrong. – vadian May 23 '20 at 08:32
  • 1
    Does this answer your question? [What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Magnas May 23 '20 at 08:35

2 Answers2

1

Seems this statement URL(string: urlString) returns nil. Check what urlString variable looks like. I think it contains unallowable characters. In this case you need to change your guard statement to

guard let urlString = urlString?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
      let url = URL(string: urlString) else {
    print("urlstring is nil or invalid")
    return
}
do {
    player = try AVAudioPlayer(contentsOf: url)
}
0

You urlString is not valid, Use this code:

guard let urlString = urlString, 
    let url = URL(string: urlString) else {
            print("url is invalid")
            return
        }
do {
    player = try AVAudioPlayer(contentsOf: url)
    player.volume = 0.5
    player.play()
} catch {
    print(error)
}


Frankenstein
  • 15,732
  • 4
  • 22
  • 47