Search code examples
iosswiftavplayer

How to track when song finished playing using AVPlayer in Swift


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

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


Solution

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