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