How can we manage play / pause events in the foreground headphones in ios

I have a requirement to handle play / pause button events on headphones in the foreground. No matter how I handle the same script in the background using the code below

if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){ [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL]; [self becomeFirstResponder]; NSLog(@"Responds!"); } 

Please help with an explanation or sample code if possible. I did a lot of research, but did not help.

+6
source share
3 answers

You should check this criterion:

  • Edit your info.plist to indicate that you are making audio (UIBackgroundModes) both in the background and in the foreground.
  • Implement this feature:

     - (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent { if (theEvent.type == UIEventTypeRemoteControl) { switch(theEvent.subtype) { case UIEventSubtypeRemoteControlTogglePlayPause: //Insert code break; case UIEventSubtypeRemoteControlPlay: //Insert code break; case UIEventSubtypeRemoteControlPause: // Insert code break; case UIEventSubtypeRemoteControlStop: //Insert code. break; default: return; } } } 

... obviously, replace the "// insert" code with any functionality that is relevant in your application.

3> Finally, for this function to be called, insert this into the viewDidAppear event:

 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; if ([self canBecomeFirstResponder]) { [self becomeFirstResponder]; } 

also see this link: http://www.sagorin.org/2011/11/29/ios-playing-audio-in-background-audio/

+11
source

There is another way to implement control of the player from the headphones. use MPRemoteCommandCenter tooglePlayPauseCommand. Apple Documentation

 [[MPRemoteCommandCenter sharedCommandCenter].togglePlayPauseCommand addTarget:self action:@selector(onTooglePlayPause)]; 
+9
source

Fast version 2 for slobodans solution:

 MPRemoteCommandCenter.sharedCommandCenter().togglePlayPauseCommand.addTarget(self, action: #selector(togglePlayStop(_:))); 
+4
source

All Articles