Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Avplayer inside tableview cell still playing when dismissing changing controller

I configure an avPlayer inside my tableview cell:

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()
}

than call this function whenever the user click a button

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

In my tableview controller i can stop the player whenever the cell is not displayed anymore like so:

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
        }
    }
}

My problem is that if from the tableview controller i switch to another controller or dismiss the controller the video is still playing. How can i stop the Player?

I need the indexpath to identify the player so i cannot call the function inside viewWillDisappear.

Hope somebody could help, I've tried to fix this for 3 days...

Thank you! ----------------------UPDATE I've tried to do so:

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
        }
    }
}

But it does not works...

like image 991
Marco Avatar asked Nov 06 '17 17:11

Marco


1 Answers

Implement viewWillDisappear to call visibleCells and cycle through them looking for a VideoCell. Each time you find one, tell it to stop playing just as in the code you already have.

like image 192
matt Avatar answered Sep 19 '22 05:09

matt