MPRemoteCommandCenter calls the handler several times in iOS

MPRemoteCommandCenter calls the handler block several times and calls unnecessary calls for selection methods.

Here is the code snippet:

MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter]; [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) { NSLog(@"NEXTTTTTT"); return MPRemoteCommandHandlerStatusSuccess; }]; [commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) { NSLog(@"PREVIOUSSS"); return MPRemoteCommandHandlerStatusSuccess; }]; 

When the user presses the next or previous button from the dock of the music player, when the screen is locked, he calls several times to call the above blocks.

+8
ios iphone ios9 music-player mpmusicplayercontroller
source share
2 answers

It looks like you have several instances of an object that you call your code, for example. if you push the new UIViewController onto the track. The old view controller may still exist and call the handler again.

Try entering the code in

 - (void)viewDidAppear:(BOOL)animated 

and then disable it like this:

 - (void)viewWillDisappear:(BOOL)animated { MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter]; [commandCenter.nextTrackCommand removeTarget:self]; [commandCenter.previousTrackCommand removeTarget:self]; } 
+7
source share

The handler will be called as many times as it is added, even if it is registered on the same object several times. Your code fragment may be called more than once.

+7
source share

All Articles