0

I am loading a AVPlayerViewController in my UITableViewCell and it works good but I am trying that when a cell is visible play video and when a cell is not visible pause video.

The problem is that the video load programmatically in the cell and when the cell disappears and reappears this loads the video again so it always start from the beginning. For example: if I press play the video and paused in the 10 seconds, then scroll to leave the video cell not visible and after i return to the video cell, it is loaded again and it gives the video in 0 seconds.

I use the function func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell for load video in my cell with the follow code:

let videoURL = NSURL(string: "url_video")
let player = AVPlayer(URL: videoURL!)

cell.av.player = player
cell.av.view.frame = cell.bounds
self.addChildViewController(cell.av)
cell.contentView.addSubview(cell.av.view)
cell.av.didMoveToParentViewController(self)
cell.av.view.translatesAutoresizingMaskIntoConstraints = false

I need the video remains paused, how can i do?

corocraft
  • 150
  • 3
  • 13

1 Answers1

3

The problem is, whenever the tableViewCell goes out of view and comes back, it's recreated. You're going to have to figure out a way to save the location of the user at each video.

Create an array with a bunch of 0's, each 0 corresponding to the time of a video in each cell.

var times = [0,0,0,0...]

Now let's say I'm on the second cell and begin to play my video. The video runs for 10 seconds and then I pause it. You can get my duration by:

AVPlayerItem *currentItem = yourAVPlayer.currentItem.currentTime

Now, I scroll past the cell, and come back to it. In your CellForRowAtIndexPath function, make sure to initialize every video with whatever value is in our array - times

You can initialize an AVPlayer video with a certain time through the help of this link: Seek to a certain position in AVPlayer right after the asset was loaded

And that's pretty much it.

Community
  • 1
  • 1
Avinash12388
  • 1,092
  • 1
  • 9
  • 19
  • Thank you, it works for me. I used this code for set time: let t1 = Int64((cell.av.player?.currentTime().value)!) let t2 = Int64((cell.av.player?.currentTime().timescale)!) let currentSeconds = t1 / t2 self.videoTime[indexPath.row] = currentSeconds – corocraft Jul 19 '16 at 17:46