Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 511
S'rCat Avatar asked Dec 14 '22 02:12

S'rCat


2 Answers

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
    ...
}
like image 114
Yuchen Avatar answered May 19 '23 01:05

Yuchen


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

like image 31
Rajat Avatar answered May 19 '23 02:05

Rajat