我正在尝试将内联视频添加到我的 UITableViewCells 中,例如 Instagram、Twitter、Vine 等。我正在使用 AVPlayerController 和自定义单元格测试带有本地视频文件的 UI(请参阅下面的示例代码)。我等待 AVPlayer 的状态为 ReadyToPlay,然后播放视频。
问题是,当在 tableView 上滚动时,每当加载视频单元格时,UI 会冻结一小部分,这使得应用程序看起来很笨重。当一行中有多个视频单元时,这种效果会变得更糟。任何想法和帮助将不胜感激
表视图代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("videoCell", forIndexPath: indexPath) as! CustomCell
//Set up video player if cell doesn't already have one
if(cell.videoPlayerController == nil){
cell.videoPlayerController = AVPlayerViewController()
cell.videoPlayerController.view.frame.size.width = cell.mediaView.frame.width
cell.videoPlayerController.view.frame.size.height = cell.mediaView.frame.height
cell.videoPlayerController.view.center = cell.mediaView.center
cell.mediaView.addSubview(cell.videoPlayerController.view)
}
//Remove old observers on cell.videoPlayer if they exist
if(cell.videoObserverSet){
cell.videoPlayer.removeObserver(cell, forKeyPath: "status")
}
let localVideoUrl: NSURL = NSBundle.mainBundle().URLForResource("videoTest", withExtension: "m4v")!
cell.videoPlayer = AVPlayer(URL:localVideoUrl)
cell.videoPlayer.addObserver(cell, forKeyPath:"status", options:NSKeyValueObservingOptions.New, context = nil)
cell.videoObserverSet = true
cell.videoPlayerController.player = cell.videoPlayer
return cell
}
自定义细胞观察者代码:
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if(keyPath=="status"){
print("status changed on cell video!");
if(self.videoPlayer.status == AVPlayerStatus.ReadyToPlay){
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.videoPlayer.play()
})
}
}
}
我还尝试使用 loadValuesAsynchronouslyForKeys(["playable"]) 加载视频的 AVAsset 版本,但这对 UI 块也没有帮助。
我该怎么做才能获得如丝般流畅的视频播放和 Instagram 滚动?