title: How do I play videos inline in a UICollectionView Swift?
body: <p>A UICollectionView will consist of a <strong>feed</strong> of videos. When the user is inline with a video, I would like it to play. With my current setup, several videos play at once (I suppose depending on the pagination) once they are loaded in to the collection view.</p>
  <blockquote>
  <p>How do I play videos inline in a UICollectionView?</p>
  </blockquote>
  <p>A cell in the UICollectionView feed will contain a UIView, which will hold the video player. This is the UIView's class <strong>PlayerViewClass</strong>:</p>
  <pre><code>import Foundation
  import UIKit
  import AVKit
  import AVFoundation
  
  class PlayerViewClass: UIView {
  
      override static var layerClass: AnyClass {
          return AVPlayerLayer.self
      }
  
      var playerLayer: AVPlayerLayer {
      
          return layer as! AVPlayerLayer
      }
  
      var player: AVPlayer? {
          get {
              return playerLayer.player
          }
      
          set {
              playerLayer.player = newValue
          }
      }
  }
  </code></pre>
  <p>The Feed's collectionView cellForItemAt indexPath delegate method in the <strong>FeedViewController</strong> is as follows:</p>
  <pre><code>override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {
  
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;cell&quot;, for: indexPath)
          
        if let cell = cell as? MyCollectionViewCell {
  
        ...
  
        //Configuring the cell
  
        ...
      
        //Video player
        let avPlayer = AVPlayer(url: post.fullURL)
          
        //Setting cell's player
        cell.playerView.playerLayer.player = avPlayer
    
        //TODO: Change so this is only executed when the user is inline.
        cell.playerView.player?.play()
      
      }
      return cell
    }
  </code></pre>
  <p>The cell <strong>MyCollectionViewCell</strong> has an IBOutlet linked to the playerView UIView:</p>
  <pre><code>class MyCollectionViewCell {
  
      @IBOutlet weak var playerView: PlayerViewClass!
  
  
  override func awakeFromNib() {
      super.awakeFromNib() 
  
     //Setup, not relevant
  
     }
  
  }
  </code></pre>
  <p>I found the following <a href="https://github.com/ashish0309/AutoVideoPlayer" rel="nofollow noreferrer">GitHub repo</a>, which shows the functionality that I would like to implement; however, I'm a little unsure of how to do this with my setup below.</p>
  <p>Thanks so much!</p>