我正在使用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()
}
}
我怎么解决这个问题?应用程序最小化后,视频应该暂停。应用程序最大化后,视频应该继续播放。