MPRemoteCommandCenter在iOS中多次调用处理程序

MPRemoteCommandCenter多次调用处理程序块,并导致对选择器方法的不必要调用.

这是代码片段:

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;
}];

当用户在屏幕锁定时点击音乐播放器底座上的下一个或上一个按钮时,会多次调用上述块.

解决方法

看起来你有多个你调用代码的对象实例,例如.如果您按轨道推送新的UIViewController.旧视图控制器可能仍然存在并再次调用处理程序.

尝试将代码放入

- (void)viewDidAppear:(BOOL)animated

然后像这样禁用它

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

以上是来客网为你收集整理的MPRemoteCommandCenter在iOS中多次调用处理程序全部内容,希望文章能够帮你解决MPRemoteCommandCenter在iOS中多次调用处理程序所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。