We have a walkie-talkie iOS app. We want to get headset button presses and we use “Remote control events” as described in https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/Remote-ControlEvents/Remote-ControlEvents.html
We have a slight variation in that we call
[[UIApplication sharedApplication] endReceivingRemoteControlEvents]; before we deactivate the audio session. The snippet is as follows and it runs on the main queue (got using dispatch_get_main_queue())
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
NSError *theError; if (unlikely(NO == [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&theError])) { NSLog(@"deactivating the audio session failed: %@", theError); } else { NSLog(@"Deactivated Audio Session"); }
The issue is that sometimes, the deactivation of our audio session does not properly notify other apps — for example, the music player does not resume music play back. It happens only around 2 out of 5 times. We found that if we did the following, it works all the time
[[UIApplication sharedApplication] endReceivingRemoteControlEvents]; void (^deactivateAudioSessionBlock)() = ^(void){ NSError *theError; if (unlikely(NO == [[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&theError])) { NSLog(@"deactivating the audio session failed: %@", theError); } else { NSLog(@"Deactivated Audio Session"); }
}; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(50 * NSEC_PER_MSEC)); dispatch_after(popTime, dispatch_get_main_queue(), deactivateAudioSessionBlock);
Basically, adding a 50 ms delay between calling [[UIApplication sharedApplication] endReceivingRemoteControlEvents]; and de-activating audio session ensures that music player resumes.
We want to understand why the 50 ms delays makes it work and want to know what is the recommended to make this code robust so that we always notify other music apps (the 50 ms is a hack that we got through experimentation)
Thanks, George |