S'rCat
S'rCat

Reputation: 638

In iOS AVPlayer, addPeriodicTimeObserverForInterval seems to be missing

I'm trying to setup AVPlayer.addPeriodicTimeObserverForInterval(). Has anyone used this successfully?

I'm using Xcode 8.1, Swift 3

Upvotes: 7

Views: 15646

Answers (2)

Yuchen
Yuchen

Reputation: 33156

The accepted answer makes it feel like that you can assign the return value to a local variable and ignore it. But according to the doc, it is actually important the hold on strong reference to the return value and removeTimeObserver(_ :).

You must maintain a strong reference the returned value as long as you want the time observer to be invoked by the player. Each invocation of this method should be paired with a corresponding call to removeTimeObserver(:) . Releasing the observer object without invoking removeTimeObserver(:) will result in undefined behaviour.

So I would do:

if let ob = self.observer {
    player.removeTimeObserver(ob)
}

let interval = CMTimeMake(1, 4) // 0.25 (1/4) seconds
self.observer = player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main) { [weak self] time in
    ...
}

Upvotes: 14

Rajat
Rajat

Reputation: 11127

Check this func addPeriodicTimeObserver(forInterval interval: CMTime, queue: DispatchQueue?, using block: @escaping (CMTime) -> Void) -> Any

It is in the documents also for example check this code snippet

let timeObserverToken = player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main) { [unowned self] time in 
}

Referenced from here

Upvotes: 4

Related Questions