Why addTarget does not get removed in Swift?

301 views Asked by At

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)
}
1

There are 1 answers

2
Sweeper On BEST ANSWER

The overload of addTarget that you are calling doesn't add self as the target. It adds an NSObject 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 to removeTarget.

Call the addTarget(handler:) method to add a block to be called. Remove the handler by calling the removeTarget(_:) method, passing in the object returned by this method.

var target: NSObject?
override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.shared.beginReceivingRemoteControlEvents()

    target = MPRemoteCommandCenter.shared().nextTrackCommand.addTarget { [unowned self] (_) -> MPRemoteCommandHandlerStatus in
        print("go to next track")
        return .success
    }
}

override func viewWillDisappear(_ animated: Bool) {
    MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(target)
}

Or, call the other overload that actually allows you to add self as a target.