Changerrs
Changerrs

Reputation: 273

Detect when AVPlayer reaches certain percentage played of the total duration?

When a user is playing a video, I am trying to figure out when the user reaches a certain percentage played.

For example, the user playing a video and I want to show some view when the user reaches 50% played.

more clarification, is there a way to setup a "listener/observer" for when 50% occurs?

Upvotes: 2

Views: 970

Answers (1)

kgaidis
kgaidis

Reputation: 15609

Best way to observe would probably be to use to periodTimeObserver from docs:

func addPeriodicTimeObserver() {
    // Invoke callback every half second
    let interval = CMTime(seconds: 0.5,
                          preferredTimescale: CMTimeScale(NSEC_PER_SEC))
    // Queue on which to invoke the callback
    let mainQueue = DispatchQueue.main
    // Add time observer
    timeObserverToken =
        player.addPeriodicTimeObserver(forInterval: interval, queue: mainQueue) {
            [weak self] time in
            // Check whether the time has reached half of duration
    }
}

Upvotes: 5

Related Questions