Search code examples
iosiphoneswiftnsnotificationcenterobservers

NSNotification being fired off more then one time?


I am creating a sample player for a test project. I created a NSNotification to call a function to play the next audio track inside an array. The issue is the notification calls this function about 8 times in a row? I have no idea why this is occurring. Here is my code and thanks for the help!

let player = AVPlayer()

var urlPlayerItems = [String]()

var currentTrack: Int = 0



    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Checks to see if player reached end
        NotificationCenter.default.addObserver(self,
                                                    selector: #selector(PlayerViewController.autoplayNextTrack(notification:)),
                                                    name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                                    object: player.currentItem)

}

    func playTrack() {

        if urlPlayerItems.count > 0 {
            let newMovieURL = URL(string: urlPlayerItems[currentTrack])!
            asset = AVURLAsset(url: newMovieURL, options: nil)

            player.play()
        }
    }



    func autoplayNextTrack(notefication: NSNotification) {
        if (currentTrack + 1) >= urlPlayerItems.count {
            currentTrack = 0
        } else {
            currentTrack += 1
        }
        playTrack()
    }

Solution

  • Aside from the fact that an observer shouldn't be set multiple times, i think that you should reset the player to zero right before calling the play function again

    func autoplayNextTrack(notefication: NSNotification) {
        player.seekToTime(kCMTimeZero)
        if (currentTrack + 1) >= urlPlayerItems.count {
            currentTrack = 0
        } else {
            currentTrack += 1
        }
    
        playTrack()
    }