skip to Main Content

I am looking for an example on how to observe AVPlayer Loop count in Swift and SwiftUI. I need to be able to communicate the loop count to firestore.

Where do I do the observing in the makeUI function, updateUI function, or in the coordinator? I am looking for help on how to structure my UIRepresentable in order to observe the loop count so I can then update my database with an accurate number.

2

Answers


  1. Chosen as BEST ANSWER

    This is the implementation of the custom AVLooper that worked, I will bind a stateobject or use a delegate to communicate loop count back to the view model to upload to firestore.

    class PlayerUIView: UIView {
        
        fileprivate var queuePlayer: AVQueuePlayer?
        fileprivate var playerLayer = AVPlayerLayer()
        fileprivate var playbackLooper: AVPlayerLooper?
        var playerItem: AVPlayerItem?
        
        var observation: NSKeyValueObservation?
    
        override init(frame: CGRect) {
        super.init(frame: frame)
            
        }
    
        required init?(coder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
        }
    
        override func layoutSubviews() {
        super.layoutSubviews()
            playerLayer.frame = bounds
            print("Will oberve loopcount")
            observation = playbackLooper?.observe(AVPlayerLooper.loopCount, options: .new) { looper, change in
                print("loop count: ", change.newValue)
            }
            
        }
        
        
        
        
    }
    

  2. There is VideoPlayer so you don’t need a Representable or Coordinator.

    You can use AVPlayerLooper and monitor the loopCount via KVO either in a StateObject if you already have one or simply an onReceive. Depends where you want to call your firestore from.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search