Update Showing Frame of AVPlayer When Using AVPlayer.seek() Prior to AVPlayer.play()

Viewed 393

I have an AVPlayer and when I get to the end of the duration, I want to go back to the beginning, but I don't want to restart the AVPlayer.

//Do something when video ended
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying(note:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)

@objc func playerDidFinishPlaying(note: Notification) {
    self.restartVideo()
}
    
func restartVideo() {
    self.player.seek(to: .zero, toleranceBefore: .zero, toleranceAfter: .zero)
}

From here, I can simply .play() the AVPlayer and it will play from the beginning. But, prior to me .play(), the .seek() function does not indicate to the user that it has been reset back to the beginning. The AVPlayer frame does not actually transition back to the first frame until AFTER I execute .play().

Question: How can I get the AVPlayer to change the actual frame it shows to the user when using the .seek() functionality?

2 Answers

This part of your code is right. It could be something else calling it to seek to end?? You can use the completion handler to see if the seek was interrupted. And also set a break point to see what queue you're on, just to make sure you're on the main thread. If a second seek operation happens you will get a false result in the completion handler. Also, try setting a break point after the seek to check if the UI responded.

    self.player.seek(to: .zero, toleranceBefore: .zero, toleranceAfter: .zero) { success in
        print("seek finished success = ", success)
    }

set like this

self.player.seek(to: .zero) // it will update the player slider to 0:00

if you want to set on specific time than use it like

// Seek to the 2 minute mark
let time = CMTime(value: 120, timescale: 1)
self.player.seek(to: time)
Related