0

我正在使用UIView组件和 AVFoundation 框架在后台显示 mp4 视频文件。

但是在应用程序用户最小化应用程序后会出现错误。因为如您所见, player.pause() 方法会导致崩溃。这是错误:Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

    import UIKit
    import AVFoundation
    import AVKit

    class ViewController: UIViewController {

    private var player: AVPlayer!

    @IBOutlet weak var videoUiViewOutlet: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupView()
    }

    private func setupView()
    {
        let path  = URL(fileURLWithPath: Bundle.main.path(forResource: "clouds", ofType: "mp4")!)
        let player = AVPlayer(url: path)
        let newLayer = AVPlayerLayer(player: player)
        newLayer.frame = self.videoUiViewOutlet.frame
        self.videoUiViewOutlet.layer.addSublayer(newLayer)
        newLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill

        player.play()

        player.actionAtItemEnd = AVPlayer.ActionAtItemEnd.none

        NotificationCenter.default.addObserver(self, selector: #selector(self.videoDidPlayToEnd(notification:)),
                                               name: NSNotification.Name(rawValue: "AVPlayerItemDidPlayToEndTimeNotification"), object: player.currentItem)

        NotificationCenter.default.addObserver(self, selector: #selector(enteredBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(enteredForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }

    @objc func videoDidPlayToEnd(notification: Notification)
    {
        let player: AVPlayerItem = notification.object as! AVPlayerItem
        player.seek(to: .zero, completionHandler: nil)
    }

    @objc func enteredBackground() {
        print("scope: enteredBackground")
        player.pause()
    }

    @objc func enteredForeground() {
        print("scope: enteredForeground")
        player.play()
    }
}

我怎么解决这个问题?应用程序最小化后,视频应该暂停。应用程序最大化后,视频应该继续播放。

4

1 回答 1

0

问题是因为您没有将值分配给player类的属性ViewController,即

private var player: AVPlayer!

并且由于它是一个强制解包 optional,因此它将nil作为其默认值。在方法中使用它enteredBackground()会导致运行时异常

解决方案:

setupView()方法中,替换

let player = AVPlayer(url: path)

self.player = AVPlayer(url: path)
于 2019-09-09T07:51:00.867 回答