Stop AVPlayer from playing in tableviewcell

2019-07-30 03:53发布

问题:

I'm using AVPlayer for displaying video in my TableViewCell. It is playing in TableViewCell , but the problem is that I'm not able to stop it. I've used this Code to play video in cellforRow

        avPlayer = AVPlayer(url: videoURL! as URL)
        playerLayer = AVPlayerLayer(player: avPlayer)
        playerLayer.frame = CGRect(x: cell.videoview.frame.origin.x, y: cell.videoview.frame.origin.x, width:cell.videoview.frame.size.width, height: cell.videoview.frame.size.height)
        cell.videoview.layer.addSublayer(playerLayer)
        avPlayer?.play()

The avPlayer and playerLayer are defined in the viewController like this

var avPlayer  : AVPlayer?
var playerLayer = AVPlayerLayer()

I'm using this code to stop the video

    self.avPlayer?.pause()
    self.playerLayer.removeFromSuperlayer()
    self.avPlayer?.rate = 0.0
    self.avPlayer?.replaceCurrentItem(with: nil)
    self.avPlayer = nil

My question is this how can I stop the video running through AVPlayer on AVPlayerLayer? Please suggest a solution, if there is any alternative for this please suggest that as well.

回答1:

Due to the reusable behavior of the cell, it releases the child view instance with itself so you have to stop it in the didEndDisplayingCell delegate method.

override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = cell as? MyCustomCell {
        if let play = player {
           print("stopped")
           play.pause()
           player = nil
           print("player deallocated")
        } else {
           print("player was already deallocated")
        }
    }
}

OR

You can get the cell instance and search the player instance and stop it.

for view in cell.subviews {
      //after comparison stop the player here
}


回答2:

AVPlayer does not have stop method. So you can set seek time to 0 and pause the player.

videoPlayer.seek(to: CMTimeMake(0, 1))
videoPlayer.pause()

Moreover, If you want to check if the videoCell is Visible or not. You can use the below code which will give you array of index of cells which are visible. So you can simply check if array contains your video cell index or not.

tableView.indexPathsForVisibleRows