If you are still compiling with iOS SDK 6.0 (as I am) you have to be a bit more indirect than @Luis E. Prado, as the requestRecordPermission method doesn't exist.
Here's how I did it. Remove the autorelease bit if you're using ARC. On iOS6 nothing happens, and on iOS7 either the 'microphone is enabled' message is logged or the alert is popped up.
AVAudioSession *session = [AVAudioSession sharedInstance];
if ([session respondsToSelector:@selector(requestRecordPermission:)]) {
[session performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
if (granted) {
// Microphone enabled code
NSLog(@"Microphone is enabled..");
}
else {
// Microphone disabled code
NSLog(@"Microphone is disabled..");
// We're in a background thread here, so jump to main thread to do UI work.
dispatch_async(dispatch_get_main_queue(), ^{
[[[[UIAlertView alloc] initWithTitle:@"Microphone Access Denied"
message:@"This app requires access to your device's Microphone.
Please enable Microphone access for this app in Settings / Privacy / Microphone"
delegate:nil
cancelButtonTitle:@"Dismiss"
otherButtonTitles:nil] autorelease] show];
});
}
}];
}
EDIT: It turns out that the withObject block is executed in a background thread, so DO NOT do any UI work in there, or your app may hang. I've adjusted the code above. A client pointed this out on what was thankfully a beta release. Apologies for the mistake.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…