I am trying to achieve smooth video scrubbing with AVPlayer
through UISlider
I have searched and it seems Apple has a Technical Q&A and explain
I know this is an old problem, I encountered it too. The solution can help someone now. Apple sample make slider super smooth and pretty. To make the sample work:
private static var context = 1
func playVideo() {
...
player.addObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem.status), options: [.new, .initial], context: &VideoViewController.context)
...
}
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath else { return }
guard context == &VideoViewController.context else { return }
switch keyPath {
case #keyPath(AVPlayer.currentItem.status):
if let newStatus = change.map({ $0[.newKey] as? NSNumber }),
let parsedNewStatus = newStatus.map({ AVPlayerItem.Status(rawValue: $0.intValue) ?? .unknown}) {
playerCurrentItemStatus = parsedNewStatus
} else {
playerCurrentItemStatus = .unknown
}
default: break
}
}
Observe and update playerCurrentItemStatus