我对iOS编码非常陌生。我正试图为我的孩子们开发一个应用程序。我有一些动物的照片和这些动物的声音。我已经成功地编写了这个应用程序:每次我点击屏幕时,图片都会发生变化,与图片相关的声音也会发生变化。过了一段时间,我得到了这个错误,应用程序挂起:
2020-05-01 12:21:31.111411+0200 Animals For Kids[1758:47571] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/andreitomescu/Desktop/iOS Developing - Udemy/Proiecte diverse/Animals For Kids/Animals For Kids/ViewController.swift, line 21第21行的代码是:
func playSound(animalName: String) {
let url = Bundle.main.url(forResource: animalName, withExtension: "wav", subdirectory: "Sounds")
**player = try! AVAudioPlayer(contentsOf: url!)** / this is the line where the error points to
player.play()
}你能帮我弄清楚这个吗?

代码第1部分:
@IBAction func imageButton(_ sender: UIButton) {
func playSound(animalName: String) {
let url = Bundle.main.url(forResource: animalName, withExtension: "wav", subdirectory: "Sounds")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}代码第2部分:
let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("Pictures")
do {
let contents = try fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles)
for item in contents
{
fileName.append(String(item.lastPathComponent.dropLast(4)))
animalName = fileName.randomElement()!代码第3部分:
let imageName = animalName
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 360, width: 414, height: 414)
view.addSubview(imageView)
}
}
catch let error as NSError {
print(error)
}
// playSound(animalName: animalName)
print(animalName)发布于 2020-05-01 11:50:30
这是由于强制展开一个零值,因为错误清楚地表明
错误:在展开可选值时意外找到零
但是为什么这个应用程序在aprox上工作8次,然后突然崩溃呢?所有文件都在URL里?
因为前8个url都是好的,所以第9个URL已经损坏了指定的URL位置,或者无法加载内容。
所以看看你的应用程序崩溃的网址。
从代码中删除强制转换。使用以下方法更新播放声音方法,并检查打印语句,并通知我
var player: AVAudioPlayer?
func playSound(animalName: String) {
guard let url = Bundle.main.url(forResource: animalName, withExtension: "wav", subdirectory: "Sounds") else {
print("path not correct")
return
}
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
print("url is not correct")
}
}发布于 2020-05-01 10:49:01
这是因为强制拆开一个零值。可能是由于在指定的URL位置没有资源,或者无法加载内容。
要了解更多关于崩溃的信息,请查看此link
https://stackoverflow.com/questions/61540930
复制相似问题