Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MPRemoteCommandCenter calls handler multiple times in iOS

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.

like image 740
Dhaval H. Nena Avatar asked Mar 19 '16 07:03

Dhaval H. Nena


2 Answers

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.

like image 54
Jason McClinsey Avatar answered Nov 07 '22 12:11

Jason McClinsey


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];
}
like image 33
reshave Avatar answered Nov 07 '22 10:11

reshave