user11270714
user11270714

Reputation:

Swift AVQueuePlayer finished playing video

I'm trying to get a notification every time a video is finished playing with my AVQueuePlayer but currently, this is only working once and then doesn't get called again.

func setupVideoPlayer(video: videos) {
    self.player.insert(AVPlayerItem(url: video), after: nil)
}

func handlePlayVideo() {
    player.play()
    print(player.currentItem)
    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { (notification) in
        print("VIDEO FINISHED")
        NotificationCenter.default.removeObserver(notification.name)
    }
}

Upvotes: 1

Views: 194

Answers (2)

Debashish Das
Debashish Das

Reputation: 919

Here,

func handlePlayVideo() {
    player.play()
    print(player.currentItem)
    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { (notification) in
        print("VIDEO FINISHED")
        NotificationCenter.default.removeObserver(notification.name)
    }
}

after first notification is received, you are removing the observer, so It will not observe to same notification second time.

remove the last line :

func handlePlayVideo() {
    player.play()
    print(player.currentItem)
    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { (notification) in
        print("VIDEO FINISHED")
    }
}

Upvotes: 3

aheze
aheze

Reputation: 30516

You are removing the observer once it's called!

NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { (notification) in
    print("VIDEO FINISHED")
    NotificationCenter.default.removeObserver(notification.name)
}

Upvotes: 0

Related Questions