swift. AVPlayer. How to track when song finished playing?

Mega4alik picture Mega4alik · Jan 6, 2015 · Viewed 33.8k times · Source

What is the east way to track when song finished playing with AVPlayer in Swift?

Is there any function which is called when avplayer finished playing, or I should combine timer with avplayer class references?

Answer

Jernej Strasner picture Jernej Strasner · Jan 7, 2015

Something like this works:

func play(url: NSURL) {
    let item = AVPlayerItem(URL: url)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerDidFinishPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: item)

    let player = AVPlayer(playerItem: item)
    player.play()
}

func playerDidFinishPlaying(note: NSNotification) {
    // Your code here
}

Don't forget to remove the observer when you're done (or in deinit)!