它在 iOS 7 中不起作用,并且如果您查看它在 iOS 7 中不起作用的原因,它在 iOS 6 中从未真正起作用。这个解决方案基于相同的代码,因此所有归功于原作者。
- 远离
mute.caf
您的 SharkfoodMuteSwitchDetector。
- 创建一个新类,称为 HASilentSwitchDetector(或其他),或替换 SharkfoodMuteSwitchDetector 中的代码。
在头文件中:
#import <AudioToolbox/AudioToolbox.h>
typedef void(^HASilentSwitchDetectorBlock)(BOOL success, BOOL silent);
@interface HASilentSwitchDetector : NSObject
+ (void)ifMute:(HASilentSwitchDetectorBlock)then;
@end
在实现文件中:
#import "HASilentSwitchDetector.h"
void MuteSoundPlaybackComplete(SystemSoundID ssID, void *clientData)
{
//Completion
NSDictionary *soundCompletion = CFBridgingRelease(clientData);
//Mute
NSTimeInterval interval = [soundCompletion[@"interval"] doubleValue];
NSTimeInterval elapsed = [NSDate timeIntervalSinceReferenceDate] - interval;
BOOL isMute = elapsed < 0.2; // mute.caf is .2s long...
//Then
HASilentSwitchDetectorBlock then = soundCompletion[@"then"];
then(YES, isMute);
//Cleanup
SystemSoundID soundID = [soundCompletion[@"soundID"] integerValue];
AudioServicesRemoveSystemSoundCompletion(soundID);
AudioServicesDisposeSystemSoundID(soundID);
}
@implementation HASilentSwitchDetector
+ (void)ifMute:(HASilentSwitchDetectorBlock)then
{
//Check
if ( !then ) {
return;
}
//Create
NSURL *url = [[NSBundle mainBundle] URLForResource:@"mute" withExtension:@"caf"];
SystemSoundID soundID;
if ( AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID) == kAudioServicesNoError ) {
//UI Sound
UInt32 yes = 1;
AudioServicesSetProperty(kAudioServicesPropertyIsUISound, sizeof(soundID), &soundID,sizeof(yes), &yes);
//Callback
NSDictionary *soundCompletion = @{@"then" : [then copy], @"soundID" : @(soundID), @"interval" : @([NSDate timeIntervalSinceReferenceDate])};
AudioServicesAddSystemSoundCompletion(soundID, CFRunLoopGetMain(), kCFRunLoopDefaultMode, MuteSoundPlaybackComplete, (void *)CFBridgingRetain(soundCompletion));
//Play
AudioServicesPlaySystemSound(soundID);
} else {
//Fail
then(NO, NO);
}
}
@end
像这样使用:
[HASilentSwitchDetector ifMute:^(BOOL success, BOOL silent) {
if ( success ) {
if ( ![[NSUserDefaults standardUserDefaults] boolForKey:forKey:kHasShownMuteWarning] && silent ) {
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:kHasShownMuteWarning];
[[[UIAlertView alloc] initWithTitle:[@"Mute Warning" localized] message:[NSString stringWithFormat:[@"This %@'s mute switch is on. To ensure your alarm will be audible, unmute your device." localized], [[[UIDevice currentDevice] isiPad]? @"iPad" : @"iPhone" localized]] delegate:nil cancelButtonTitle:nil otherButtonTitles:[@"Ok" localized], nil] show];
}
}
}];