Lose Youtube player when it scrolls out of view because of reusable cells in table view

606 Views Asked by At

I am building a instagram like news feed. Each post is either a spotify streaming song or a Youtube video playing in its own YTplayer view. If I play a video cell and then scroll through the feed, the video keeps playing even though you cant see it. At this point, if I scroll to a spotify post and hit play, I want the video to stop playing. I am not able to do this. I tried to keep track of the 'last played' video cell and stop the YTplayer instance, but the cell is reused by that point and doesn't exist. So I can't do it that way. Does anyone have any ideas as to how I can do this?

My Custom tableview cell class has the YTplayer view, I only load some of the cells with youtube video ID's, which become the Youtube video cells when the table view is loaded.

2

There are 2 best solutions below

1
virajd On BEST ANSWER

I solved it. Right after my dequeueReusableCell I check if the cell contains a video post. I use a string flag I set in the post to do this. If it does, I declare my tableview controller as its playback delegate. From there on, if I play that cell and scroll to a spotify cell and play that one, I use player.stopVideo() to stop the Youtube player.

1
Shehata Gamal On

I think you need to implement

func tableView(_ tableView: UITableView,
           didEndDisplaying cell: UITableViewCell,
           forRowAt indexPath: IndexPath) {

   // access the playing video of the cell and stop it 

}