MPRemoteCommandCenter calls handler multiple times in iOS
Asked Answered
C

2

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.

Chef answered 19/3, 2016 at 7:9 Comment(0)
D
14

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.

Desert answered 31/5, 2016 at 18:56 Comment(0)
D
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];
}
Dentist answered 28/3, 2016 at 9:14 Comment(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.Chef
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(<previouslyStoredValue>).Lorient

© 2022 - 2024 — McMap. All rights reserved.