尝试在PiP模式下的播放器中将当前的AVPlayerItem替换为另一个AVPlayerItem。我在iOS 11.3和iOS 11.4版本中遇到问题。每当使用新视频实例化新播放器项目并尝试播放时,都会删除播放器。它的奇怪行为。有人遇到过类似的问题吗?
采取的方法: 1.创建一个包含视频网址列表的表格视图 2.创建一个AVPlayerViewController()实例 3.在tableView(_ tableView:UITableView,didSelectRowAt indexPath:IndexPath)中尝试用新的视频URL替换AVPlayerItem。
附加代码以获取更多信息
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let videoURL = NSURL(string: self.videosListArray[indexPath.row])
if playerViewController.player != nil {
playerViewController.player!.replaceCurrentItem(with: AVPlayerItem (url: videoURL! as URL))
} else {
let player = AVPlayer(url: videoURL! as URL)
playerViewController.player = player
self.present(playerViewController, animated: true){
self.playerViewController.delegate = self
self.playerViewController.player!.play()
}
}
}
//Below implementation is for making the user to select other videos from tableview.
func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController) {
playerViewController.allowsPictureInPicturePlayback = true
playerViewController.player!.play()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
playerViewController.dismiss(animated: true, completion: nil)
}
}
func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {
let currentViewController = navigationController?.visibleViewController
if currentViewController != playerViewController {
if let topViewController =
navigationController?.topViewController {
topViewController.present(playerViewController,
animated: false, completion: {()
completionHandler(true)
})
}
}
}