title: video plays a couple of times in a tableview cell and then it wont work - swift ios
body: <p>I am currently creating a feed with a table view playing videos from internet and then I am saving them in the cache, this is working fine. the problem is that after I scroll up and scroll down a couple of times to test that is working on other cells, the uiview where I am adding the videos gets black and doesn't reproduce the video. <a href="https://i.stack.imgur.com/58zl9.jpg" rel="nofollow noreferrer">video preview</a> The weird part, is that it works great on the simulator and this never happens but it does on my phone.  I appreciate your help.</p>
  
  <p>this is the code for mi tableViewCell, I check is the post has a video, if so I do a cache from the url and assign it to the avplayer</p>
  
  <pre><code>  import UIKit
    import AVFoundation
    import Alamofire
    import Firebase
    import AVKit
  
  class PostCell: UITableViewCell {
  
  @IBOutlet weak var postImageView: UIImageView!
  
  @IBOutlet weak var numberOfLikes: UIButton!
  @IBOutlet weak var usernameLbl: UILabel!
  
  @IBOutlet weak var likesBtn: UIButton!
  @IBOutlet weak var commentsBubbleBtn: UIButton!
  
  @IBOutlet weak var addCommentBtn: UIButton!
  @IBOutlet weak var dotsBtn: UIButton!
  @IBOutlet weak var profilePic: UIImageView!
  @IBOutlet weak var postCaptionLbl: UILabel!
  @IBOutlet weak var timeAgoLbl: UILabel!
  @IBOutlet weak var videoView: UIView!
  @IBOutlet weak var soundBtn: UIButton!
  
  var userUIDtoSend = ""
  var audio = true
  var like = Bool()
  var postID = ""
  var player: AVPlayer!
  var playerLayer: AVPlayerLayer?
  var playerCache = [String: AVPlayer]()
  var videoIsPlaying = false
  
  
  var url : URL?
  
  
  func updateUI(postImageView: String, caption: String, type: String, profilePic: String, username: String, postUID: String) {
  
      postCaptionLbl.text = caption
      timeAgoLbl.text = "1h ago"
      self.postID = postUID
  
      soundBtn.layer.borderWidth = 2.0
      soundBtn.layer.cornerRadius = 4.0
      soundBtn.layer.borderColor = soundBtn.tintColor.cgColor
      soundBtn.layer.masksToBounds = true
      self.profilePic.downloadImage(from: profilePic)
      self.profilePic.sd_setImage(with: URL(string: profilePic))
      self.usernameLbl.text = username
  
      let tapLikes = UITapGestureRecognizer()
      tapLikes.addTarget(self, action: #selector(likeBtnWasPressed))
      likesBtn.addGestureRecognizer(tapLikes)
      likesBtn.isUserInteractionEnabled = true
  
       checkLikes()
  
  
      if type == "video" {
        //  print("Video is PLAYING")
          self.videoIsPlaying = true
          self.soundBtn.isHidden = false
          let tapRec = UITapGestureRecognizer()
          tapRec.addTarget(self, action: #selector(self.audioToggle))
          self.soundBtn.addGestureRecognizer(tapRec)
          self.soundBtn.isUserInteractionEnabled = true
          self.videoView.isHidden = false
          self.postImageView.isHidden = true
  
  
  
          CacheManager.shared.getFileWith(stringUrl: postImageView) { result in
  
              switch result {
              case .success(let url2):
                  //self.url = URL(fileURLWithPath: "\(url2)")
                  self.url = URL(string: "\(url2)")
                  self.player = AVPlayer(url: self.url!)
                  //
  
                     //self.player?.automaticallyWaitsToMinimizeStalling = true
  
                  self.playerLayer = AVPlayerLayer(player: self.player)
                  self.playerLayer?.frame = self.videoView.bounds
  
                  //      //self.playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
                  self.player?.play()
                  self.videoView.layer.addSublayer(self.playerLayer!)
                  self.player!.isMuted = self.audio
  
                  NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player!.currentItem)
  
                  print("\n\n\n\n")
                  print("error in the player:", self.player.error ?? "no error")
                 // print("Post tile: ", self.postCaptionLbl.text ?? "")
                  print("ready for display: " ,self.playerLayer!.isReadyForDisplay)
  
              case .failure(let error):
                  // handle errror
                  print("this is the fucking error from video: ", error)
  
  
                  self.url = URL(string: postImageView)!
                  self.player = AVPlayer(url: self.url!)
                  self.playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
                  self.player?.automaticallyWaitsToMinimizeStalling = false
                  self.player?.isMuted = self.audio
                  self.playerLayer = AVPlayerLayer(player: self.player)
                  self.playerLayer?.frame = self.videoView.frame
                  self.videoView.layer.addSublayer(self.playerLayer!)
  
                  self.player?.play()
                  NotificationCenter.default.addObserver(self, selector: #selector(self.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
                  print("this is player cache", self.playerCache)
  
              }
          }
  
      } else {
  
          self.videoIsPlaying = false
          NotificationCenter.default.removeObserver(self)
        //  print("DISPLAYING IMAGE")
          self.soundBtn.isHidden = true
          self.videoView.isHidden = true
          self.postImageView.isHidden = false
          player?.pause()
          self.postImageView.sd_setShowActivityIndicatorView(true)
          self.postImageView.sd_setIndicatorStyle(.gray)
          self.postImageView.sd_setImage(with: URL(string: postImageView))
      }
  
  
  }
  
  func pauseVideo() {
      if self.player != nil {
          self.player!.seek(to: kCMTimeZero)
          self.player!.pause()
      }
  }
  
  override func prepareForReuse() {
      super.prepareForReuse()
      playerLayer?.removeFromSuperlayer()
      player?.pause()
  }
  
  
  
  
  
  @objc fileprivate func playerItemDidReachEnd(_ notification: Notification) {
      if self.player != nil {
          self.player!.seek(to: kCMTimeZero)
          self.player!.play()
      }
  }
  
  
  
  
  @objc func audioToggle(){
      print("tapped")
  
      if self.player?.isMuted == true {
          self.player?.isMuted = false
          self.soundBtn.setTitle("Mute", for: .normal)
  
      } else {
          self.player?.isMuted = true
          self.soundBtn.setTitle("Sound", for: .normal)
      }
      }
  
  }
  </code></pre>
  
  <p>I tried in a collection view in another viewController and this happens as well. It seems it something wring whit the avplayer when it runs in actual device.</p>