Search code examples
iosswift3avplayerseconds

how to check when AV player reach special Seconds in swift 3


I have an AVPlayer and want to do some thing:

When the video passes 5 seconds or more, print "OK" and when the current time is less than 5 seconds, print(No).

I know that I should use observer. But I didn't get the result. The code here is working well, but not automatically. The code works just during the button action. But I want this code to run automatically.

Here is my code:

override func viewDidLoad() {
    super.viewDidLoad()        
    let currentPlayerItem = Player.currentItem
    let duration = currentPlayerItem?.asset.duration

    let currentTime = Float(self.Player.currentTime().value)


        if currentTime >= 5 {

            print("OK")

        }else if currentTime <= 5 {

            print("NO")
        }

    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.Player.currentItem, queue: nil, using: { (_) in
        DispatchQueue.main.async {
            self.Player.seek(to: kCMTimeZero)
            self.Player.play()
        }
    })

As you see, I have observer to play again when the video is finished. I want to use this observer when reaching 5th second of the video.


Solution

  • After calling play() add a block that runs after 5 secs. Then check if player is still playing.

    self.Player.play()
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5.0) {
        // check if player is still playing
        if self.Player.rate != 0 {
            print("OK")
            print("Player reached 5 seconds")
        }
    }