swiftxcodeavplayermpremotecommandcenter

Swift MPRemoteCommandCenter nextTrackCommand gets called 3 times


I am using MPRemoteCommandCenter to change song in my music radio app. But when I press next track button from lock screen it jumps 3 steps insted of one.

Here is my code:

func setupRemoteTransportControls() {
        let commandCenter = MPRemoteCommandCenter.shared()

        commandCenter.nextTrackCommand.addTarget { [unowned self]     event in
        print("Next")
        self.stationIndex = (self.stationIndex+1)
        self.currentStation = self.stations[self.stationIndex]
            return .success
        }
}

The output is: Next Next Next

But I only press the button once. What can I do to only output it once insted of 3 times?


Solution

  • The problem is likely that you are calling setupRemoteTransportControls multiple times. Every time you do, you call commandCenter.nextTrackCommand.addTarget and set up a new action-target pair (without removing the existing one). So when the user presses the button, all of those pairs fire.