我必须在tableView单元格中的App中播放视频。根据查看屏幕尺寸我的表可以在小屏幕设备中显示2个单元,在iPhone XSMax或Xr等大屏幕设备中显示3个单元
Flow AVPlayerController
Class Created
class CustomAVPlayerViewController: AVPlayerViewController {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("touchesBegan")
}
}
实例在单元类中创建
var myImgArray=[String]()
var myVideoArray=[String]()
var myVideoPlayer : AVPlayer?
var videoPlayerController : CustomAVPlayerViewController?
var myPlayerItems=[AVPlayerItem]()
准备重用功能
override func prepareForReuse() {
myVideoPlayer?.replaceCurrentItem(with: nil)
videoPlayerController=nil
myVideoPlayer=nil
self.count=0
myPlayerItems.removeAll()
myImgArray.removeAll()
myVideoArray.removeAll()
NotificationCenter.default.removeObserver(NSNotification.Name.AVPlayerItemDidPlayToEndTime)
for vieww in myScrollView.subviews {
vieww.removeFromSuperview()
}
}
我正在使用AVPLayer
实例一个单元格。单个单元格可以包含多个视频,因此使用了滚动视图
if !videoArray.isEmpty {
/// We've Videos
for i in 0..<videoArray.count {
///Get Origin
let xOrigin : CGFloat = CGFloat(i) * myScrollView.frame.size.width + (CGFloat(imgArray.count)*myScrollView.frame.size.width)
let newPlayerItem = AVPlayerItem(url: URL(string: videoArray[i])!)
myPlayerItems.append(newPlayerItem)
if i == 0 {
self.myVideoPlayer=AVPlayer(playerItem: newPlayerItem)
self.videoPlayerController = CustomAVPlayerViewController()
NotificationCenter.default.removeObserver(NSNotification.Name.AVPlayerItemDidPlayToEndTime)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.myVideoPlayer!.currentItem)
self.videoPlayerController?.player = self.myVideoPlayer!
self.videoPlayerController?.view.frame = CGRect(x: xOrigin+10, y: 10, width: self.myScrollView.frame.size.width-20, height: self.myScrollView.frame.size.height-20)
self.myVideoPlayer?.play()
myScrollView.addSubview(self.videoPlayerController!.view)
myScrollView.bringSubviewToFront(self.videoPlayerController!.view)
}
}
}
如上面的代码所示,我循环遍历视频阵列并在scrollView中添加其子视图
问题 -
当屏幕上有多个具有视频的下行单元或具有视频的下一个单元时,它开始滞后
我使用prepareForReuse
来避免高内存使用。应用程序在4分钟的运行中循环到40 MB,其中包括其他功能
我可以做什么 ?
尝试过的事情
IndexPathForVisibleCell
它包括三个单元格,一旦我的单元格离开屏幕显示我删除scrollView子视图和AVPLayer实例。AVPLayer
实例但没有奏效。它不播放视频原因 - 当三个单元格在屏幕上时它不会再次出列,因此视频将不会被加载,因为全局实例将仅添加到一个并且prepareForReuse导致无法播放视频它可能会滞后,因为您添加和删除AVPlayer视图。您可以重复使用它们,而不是删除它们,以便在屏幕上显示单元格时更新链接。你可以参考这样的文章:Best way to check if UITableViewCell is completely visible