我在一个单元格中有一个视频,如果我用按钮将其置于PIP模式,一切都会正常工作,但如果我以编程方式进行操作,当单元格离开屏幕时,不会自动置于PIP模式,可以通过按钮激活它吗?
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let cell = self.playerCell, self.playerController != nil else {
return
}
let rect = self.view.convert(cell.frame, from: scrollView)
if rect.origin.y < 0, self.pipController == nil {
self.pipController = self.startPictureInPicture()
}
}
func startPictureInPicture() -> AVPictureInPictureController? {
guard AVPictureInPictureController.isPictureInPictureSupported() else {
return nil
}
let layer = AVPlayerLayer(player: self.playerController.player)
try? AVAudioSession.sharedInstance().setActive(true)
if let pipController = AVPictureInPictureController(playerLayer: layer) {
if pipController.isPictureInPicturePossible {
pipController.startPictureInPicture()
} else {
pipController.addObserver(self, forKeyPath: "isPictureInPicturePossible", options: [.new, .initial], context: nil)
}
}
return nil
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "isPictureInPicturePossible", let pipController = object as? AVPictureInPictureController, pipController.isPictureInPicturePossible {
pipController.startPictureInPicture()
}
}
UPDATE:调试控制台始终显示警告对<UIViewController>。但我已经用解决了这个问题
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
pipController.startPictureInPicture()
}
根据苹果的指导方针,我们不应该在没有用户操作的情况下启动PIP模式。
只开始画中画播放以响应用户交互,而从不以编程方式播放。应用商店审查小组拒绝未遵守此要求的应用。
来源:https://developer.apple.com/documentation/avkit/adopting_picture_in_picture_in_a_custom_player
我建议你在应用程序中创建自己的自定义PIP视图,以避免被拒绝。