Mega4alik Mega4alik - 2 months ago 28
Swift Question

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

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

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)!