当取消更换控制器时,桌面单元格内的Swift Avplayer仍在播放

时间:2017-11-06 17:30:08

标签: ios swift uitableview avplayer

我在tableview单元格中配置了一个avPlayer:

func createPlayer(url: URL) {
    self.playerCell = AVPlayer(url: url)
    self.videoContainerView.playerLayer.bounds = self.videoContainerView.bounds
    self.videoContainerView.playerLayer.videoGravity = .resizeAspectFill
    self.videoContainerView.playerLayer.player = playerCell
     playerCell?.play()
}

每当用户点击按钮

时调用此函数
@IBAction func playBtnPressed(_ sender: Any) {
    if let videoUrlString = post?.mediaUrl, let url = URL(string: videoUrlString) {
        createPlayer(url: url)
    }
    playBtn.isHidden = true
}

在我的tableview控制器中,只要不再显示单元格,我就可以停止播放器:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as? VideoCell else {return}
    if cell.playerCell != nil {
        if (cell.playerCell?.rate != 0) && (cell.playerCell?.error == nil) {
            cell.playerCell?.pause()
            cell.playerCell = nil
            cell.playBtn.isHidden = false
        }
    }
}

我的问题是,如果从tableview控制器切换到另一个控制器或关闭控制器,视频仍在播放。 我该如何阻止播放器?

我需要索引路径来识别播放器,所以我无法调用viewWillDisappear中的函数。

希望有人可以提供帮助,我已经尝试解决这个问题3天了......

谢谢! ---------------------- UPDATE 我试过这样做:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
 guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? VideoCell else {return}
    if cell.playerCell != nil {
        if (cell.playerCell?.rate != 0) && (cell.playerCell?.error == nil) {
            cell.playerCell?.pause()
            cell.playerCell = nil
            cell.playBtn.isHidden = false
        }
    }
}

但它不起作用......

4 个答案:

答案 0 :(得分:1)

实施viewWillDisappear来呼叫visibleCells并循环查找VideoCell。每次找到一个,告诉它停止播放,就像你已经拥有的代码一样。

答案 1 :(得分:1)

更优雅的解决方案是覆盖func prepareForReuse()并暂停播放器。删除它可能不是最好的事情,因为从单元格到单元格可以替换AVPlayer实例中的当前项目 avPlayer?.replaceCurrentItem(with:videoPlayerItem)

答案 2 :(得分:0)

这对我有用

override func viewWillDisappear(_ animated: Bool) {

    let indexPath = self.tableView.indexPathsForVisibleRows
    for i in indexPath! {

        let cell : myCustomCell = self.tableView.cellForRow(at: i) as! MyCustomCell

        cell.mmPlayerLayer.player?.pause()

    }

}

答案 3 :(得分:0)

您可以使用它,就像viewWillDisappear

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard let cell = cell as? YouTableViewCell else { return }
    DispatchQueue.main.async {
         cell.videoPlayer.player?.pause()
         cell.videoPlayer.player = nil
         cell.videoPlayer.layoutIfNeeded()
   }

}