I have a tableView which gets data from the database. Some of the cells in my TableView contain videos in them and when we come across a video it displays properly.
My issue is that if someone keeps scrolling then that video still keeps playing. I would like to change that and if the user watches part of a video then keeps scrolling then I would like to end the video right there. I think I'm close to solving that issue but not quite there yet.
This is my code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Home", for: indexPath) as! Home
let filename = streamsModel.video_image[indexPath.row] as NSString
if filename.pathExtension == "mov" {
let movieURL = URL(string: streamsModel.video_image[indexPath.row])
cell.videoCapHeight.constant = CGFloat(Float(cell.pic_height!))
cell.playerView = AVPlayer(url: movieURL!)
cell.MyAVPlayer.player = cell.playerView
cell.MyAVPlayer.showsPlaybackControls = false
cell.MyAVPlayer.view.frame = cell.videoView.bounds
cell.videoView.addSubview(cell.MyAVPlayer.view)
controller.addChildViewController(cell.MyAVPlayer)
cell.playerView?.isMuted = false
cell.MyAVPlayer.player?.play()
}
return cell
}
That code above simply checks to see if the streamsModel.video_image has a .mov extension (JSON). If it does, then it gets the movie/video and displays it in a AVPlayer.
As you can see from the code, the Play() method is used so videos start playing automatically. The problem is that if a video is, for instance, 1 minute long and you watch 20 seconds of it and you scroll down, you still hear that video playing and I would like to stop the video as soon as the user scrolls away.
This is my scrollView code now I just need to stop the videos here on scroll or maybe in UITableViewCell:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (self.lastContentOffset > scrollView.contentOffset.y + 0) {
print("scrolling up")
}
else if (self.lastContentOffset < scrollView.contentOffset.y) {
print("scrolling down")
}
self.lastContentOffset = scrollView.contentOffset.y
}