i am very new to iOS coding. I am trying to build an app for my kids. I have some pictures with animals and the sound that these animals do. I've managed to code the app: each time I tap on the screen, the picture changes and the sound related to the picture changes also. After some time, I get this error and the app hangs:
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
the code at line 21 is:
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()
}
Can you please help me figure this one out?
Code part 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()
}
Code part 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()!
Code part 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)