CodexBloom - Programming Q&A Platform

Issues with UISlider and AVPlayer not updating in real-time on iOS 16

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-08
ios avplayer uislider swift

I'm facing a situation where I have an `AVPlayer` instance that is supposed to be controlled by a `UISlider`. The slider is meant to reflect the current playback time of the video in real-time. However, I notice that the slider does not update correctly as the video plays, especially when the video is paused or scrubbed. I have implemented the following code: ```swift import UIKit import AVKit class VideoPlayerViewController: UIViewController { var player: AVPlayer! var playerLayer: AVPlayerLayer! @IBOutlet weak var slider: UISlider! override func viewDidLoad() { super.viewDidLoad() setupPlayer() startObservingTime() } func setupPlayer() { guard let url = URL(string: "https://example.com/video.mp4") else { return } player = AVPlayer(url: url) playerLayer = AVPlayerLayer(player: player) playerLayer.frame = view.bounds view.layer.addSublayer(playerLayer) player.play() } func startObservingTime() { // This observer is not updating the slider in real-time player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 600), queue: DispatchQueue.main) { [weak self] time in self?.slider.value = Float(CMTimeGetSeconds(time)) } } @IBAction func sliderValueChanged(_ sender: UISlider) { let newTime = CMTime(seconds: Double(sender.value), preferredTimescale: 600) player.seek(to: newTime) } } ``` Despite setting the time observer, the `UISlider` only updates when I pause and play the video again, rather than in real-time while playing. I also checked if the `addPeriodicTimeObserver` method was being called, and it is. I’ve tried using different intervals for the observer, but the results remain the same. Additionally, I ensured the slider's value is being set correctly based on the current playback time. Is there something I'm missing, or is there a known issue with the `AVPlayer` and `UISlider` interactions on iOS 16? Any insights would be appreciated! What's the best practice here? The project is a microservice built with Swift. Thanks, I really appreciate it!