对于我的 SwiftUI 应用程序,我正在尝试创建一个单例来控制 AVPlayer 和 AVPlayerLayer,以便我可以控制 TabView 的每个页面上的视频播放。我认为我在这里犯了一个相当低级的错误,但我不太明白这个问题。我收到此错误:
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
从这一行:
self.pipController = AVPictureInPictureController(playerLayer: self.playerLayer)
看起来
super.init()
干扰了我在 init() 中分配属性的能力,但我不确定为什么。能解释一下吗?
全班同学:
import Foundation
import AVFoundation
import AVKit
// A singleton to control a globally available AVPlayer and AVPlayerLayer
@MainActor
final class GlobalVideoPlayerController: NSObject, AVPictureInPictureControllerDelegate {
let player: AVPlayer = AVPlayer()
let playerLayer = AVPlayerLayer()
var pipController: AVPictureInPictureController!
var pipPossibleObservation: NSKeyValueObservation?
static let shared = GlobalVideoPlayerController()
private override init() {
super.init()
self.playerLayer.player = self.player
self.pipController = AVPictureInPictureController(playerLayer: self.playerLayer)
self.pipController.delegate = self
}
func setupPictureInPicture() {
// Ensure PiP is supported by current device.
if AVPictureInPictureController.isPictureInPictureSupported() {
// Create a new controller, passing the reference to the AVPlayerLayer.
pipPossibleObservation = pipController.observe(\AVPictureInPictureController.isPictureInPicturePossible,
options: [.initial, .new]) { [weak self] _, change in
// Update the PiP button's enabled state.
// self?.pipButton.isEnabled = change.newValue ?? false
}
} else {
// PiP isn't supported by the current device. Disable the PiP button.
// pipButton.isEnabled = false
}
}
}
init(playerLayer:)
是一个失败的初始化器。当设备不支持画中画时,它将失败(评估为nil
)。
类方法验证当前设备是否支持画中画。尝试在不受支持的设备上创建画中画控制器将返回 nil。isPictureInPictureSupported()
据我所知,您可能正在模拟器上运行此程序,该模拟器不支持画中画。
pipController
设置为nil,因此pipController.delegate
的访问崩溃。您可以通过删除 pipController.delegate = self
行来验证这一点。 Xcode 由于某种原因(可能是一个差一错误)将错误消息放在上一行。
在任何情况下,您都不应该将
pipController
设为隐式展开的可选选项,因为某些设备不支持画中画,您应该适当处理这种情况。