The target of nextTrackCommand
is called multiple times when I navigate back from a screen and enter the screen again even tho i remove the target in viewWillDisappear
. What did I do wrong?
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.shared.beginReceivingRemoteControlEvents()
MPRemoteCommandCenter.shared().nextTrackCommand.addTarget { [unowned self] (_) -> MPRemoteCommandHandlerStatus in
print("go to next track")
return .success
}
}
override func viewWillDisappear(_ animated: Bool) {
MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(self)
}
The overload of
addTarget
that you are calling doesn't addself
as the target. It adds anNSObject
object that you didn't know about before as the target. It returns this object. So if you want to remove it, you should get its return value, hold it in a property, so that you can pass it toremoveTarget
.Or, call the other overload that actually allows you to add
self
as a target.