I am trying to make audio playback controllable from the command center. The audio is being played from a view that has a new instance created every time a segue is triggered from the file list when a file is selected for playing.
The code that configures the command center controls is present in the viewDidLoad
function of the player view:
let audioSession = AVAudioSession.sharedInstance();
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback);
try AVAudioSession.sharedInstance().setActive(true);
} catch {}
UIApplication.shared.beginReceivingRemoteControlEvents();
TableViewController.commandCenter = MPRemoteCommandCenter.shared();
TableViewController.commandCenter!.togglePlayPauseCommand.isEnabled = true;
TableViewController.commandCenter!.togglePlayPauseCommand.addTarget(self, action: #selector(TableViewController.playbacker!.TogglePlayPause))
The first time I am entering the player view, the control center commands work perfectly fine. The problem arises when I am selecting another file for playback and the view is recreated. Then I am presented with the following exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_MPWeakInvocationTarget TogglePlayPause]: unrecognized selector sent to instance 0x170032340'
I have tried making the MPRemoteCommandCenter
variable static, the player view reference static, but the results are the same.
Could anybody please give me some indication on why is this not working?