1

I am loading videos in AVPlayer in collection view. Some cells repeat data. How to resolve this issue?

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell:homecollCell = self.collectionview.dequeueReusableCell(withReuseIdentifier: "homecollCell", for: indexPath) as! homecollCell
    //cell.player?.pause()

    let obj = self.friends_array[indexPath.row] as! Home

    cell.img.sd_setImage(with: URL(string:self.appDelegate.imgbaseUrl!+obj.thum), placeholderImage: UIImage(named: ""))

    let url = URL.init(string: self.appDelegate.imgbaseUrl!+obj.video_url)

    let screenSize: CGRect = UIScreen.main.bounds
    cell.playerItem = AVPlayerItem(url: url!)
    //cell.player!.replaceCurrentItem(with: cell.playerItem)
    cell.player = AVPlayer(playerItem: cell.playerItem!)
    cell.playerLayer = AVPlayerLayer(player: cell.player!)
    cell.playerLayer!.frame = CGRect(x:0,y:0,width:screenSize.width,height: screenSize.height)
    cell.playerLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cell.playerView.layer.addSublayer(cell.playerLayer!)

    cell.player?.play()
Andrei Konstantinov
  • 6,971
  • 4
  • 41
  • 57

1 Answers1

2

Cells are reusable so you have to remove or discard the changes what you have done on other cells using prepareForReuse(). Simply like this. Call this inside cell.

override func prepareForReuse() {
     super.prepareForReuse()
     self.label.text = nil
}
Andrei Konstantinov
  • 6,971
  • 4
  • 41
  • 57
Pranavan SP
  • 1,785
  • 1
  • 17
  • 33