如何从PlayCommand中删除目标?

时间:2018-06-08 08:48:50

标签: c# ios xamarin xamarin.ios avplayer

我正在使用XamarinMediaManager Xamarin.iOS 上构建一个audioPlayer,它基于iOS上的AVPlayer

要从锁定屏幕播放/暂停曲目,我将以下处理程序添加到PlayCommandPauseCommand,如下所示:

MPRemoteCommandCenter.Shared.PlayCommand.AddTarget(LockScreenPlay);
MPRemoteCommandCenter.Shared.PauseCommand.AddTarget(LockScreenPause);
 //..

 private MPRemoteCommandHandlerStatus LockScreenPlay(MPRemoteCommandEvent arg)
{
  //..
    PlaybackController.Play();
  // ..
}
 private MPRemoteCommandHandlerStatus LockScreenPause(MPRemoteCommandEvent arg)
{
 //..
    PlaybackController.Pause();
 //..
}

问题

当我多次访问控制器LockScreenPlay/Pause多次执行时,如何在卸载View时删除旧的处理程序?

Ps:我已经尝试RemoveTarget方法ViewWillDisappear

KMPRemoteCommandCenter.Shared.PlayCommand.RemoveTarget(this);

但那不起作用,我做错了什么?任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:1)

MPRemoteCommandCenter.Shared.PlayCommand.AddTarget(LockScreenPlay);将返回NSObject。如果你想删除这个动作,你应该使用这个api:

// Add play command
playCommand =  MPRemoteCommandCenter.Shared.PlayCommand.AddTarget(LockScreenPlay);
// Remove play command later
MPRemoteCommandCenter.Shared.PlayCommand.RemoveTarget(playCommand);

这样,您每次添加时都需要记录命令。然后在需要时将其删除。

您也可以尝试使用OC选择器添加播放命令:

MPRemoteCommandCenter.Shared.PlayCommand.AddTarget(this, new ObjCRuntime.Selector("LockScreenPlay:"));
[Export("LockScreenPlay:")]
private void LockScreenPlay(MPRemoteCommand command)
{
   ...
}

通过这种方式,您可以使用MPRemoteCommandCenter.Shared.PlayCommand.RemoveTarget(this);删除已添加的所有命令。暂停命令也是如此。