我一直遇到此错误,有人可以尝试帮助我解决此问题

时间:2020-05-23 08:27:13

标签: swift

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")
    }

错误代码:线程1:致命错误:在展开可选值时意外发现nil

2 个答案:

答案 0 :(得分:1)

似乎该语句URL(string: urlString)返回nil。检查urlString变量的外观。我认为它包含不允许的字符。在这种情况下,您需要将guard语句更改为

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)
}

答案 1 :(得分:0)

urlString无效,请使用以下代码:

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)
}