14

MPRemoteCommandCenter calls the handler block multiple times and causes unnecessary calls to selector methods.

Here is 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 user clicks on next or previous button from the music player dock while screen is locked it causes multiple times to call the above blocks.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dhaval H. Nena
  • 3,992
  • 1
  • 37
  • 50

2 Answers2

12

The handler will be called as many times as it is added, even if it is registered on the same object multiple times. Perhaps your code snippet is called more than once.

Jason McClinsey
  • 426
  • 5
  • 12
11

It looks like you have multiple instances of the object you call your code, eg. if your pushing a new UIViewController per track. The old view controller might still exist and call the handler again.

Try to put your 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];
}
reshave
  • 111
  • 2
  • Thanks for the answer I think this should be the solution. Any way I managed to prevent multiple calls by checking time interval since the last click on button. – Dhaval H. Nena Jun 01 '16 at 05:17
  • 3
    It should be noted, that `removeTarget:self` only works if you added a target with the `addTarget(_:action:)` signature. If you use the closure signature (`addTarget(handler:)`) you have to retain the returned token (`Any`) and use this to resolve the target relationship. `command.removeTarget()`. – fruitcoder Jun 29 '17 at 14:05