Ошибка Swift: Поток 1: Неустранимая ошибка: неожиданно обнаружен ноль при развертывании необязательного значения - PullRequest
0 голосов
/ 31 января 2019

Я получаю эту проблему в своем коде:

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

Это сообщение появляется в этой строке моего кода:

try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))

Любая помощь будет принята с благодарностью.Заранее спасибо!

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {

        if event?.subtype == UIEvent.EventSubtype.motionShake {

            let fileLocation = Bundle.main.path(forResource: "sound1", ofType: "mp3")

            do {
                try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation!))
                player.play()
            } catch {
                // process error   
            }   
        }   
    }
}

1 Ответ

0 голосов
/ 31 января 2019

Ваш файл не найден.

Я внес небольшие изменения, чтобы помочь отладке и предотвратить сбой.

import UIKit
import AVKit

class ViewController: UIViewController {

    var player = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {

        if event?.subtype == UIEvent.EventSubtype.motionShake {
            if let fileLocation = Bundle.main.path(forResource: "sound1", ofType: "mp3") {
                do {
                    let player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileLocation))
                    player.play()
                } catch (_) {
                    print("AVAudioPlayer could not play the file.")
                }
            } else {
                print("File was not be found.")
            }
        }
    }
}
...