Search code examples
iosswiftswiftui

How do I observe AVPlayerLooper Loop Count?


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.


Solution

  • 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)
            }
            
        }
        
        
        
        
    }