Last active
July 11, 2022 06:52
-
-
Save niw/a739e43d1f8ea4ecfa86ab171719a4d3 to your computer and use it in GitHub Desktop.
Get current iPhone/iPad ringer switch (mute switch) state and change events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import Foundation; | |
NS_ASSUME_NONNULL_BEGIN | |
FOUNDATION_EXTERN NSString * const RingerSwitchDidChangedNotification; | |
@interface RingerSwitchObserver : NSObject | |
@property (nonatomic, readonly, getter=isSlient) BOOL silent; | |
+ (instancetype)sharedObserver; | |
@end | |
NS_ASSUME_NONNULL_END |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "RingerSwitchObserver.h" | |
#import <notify.h> | |
NS_ASSUME_NONNULL_BEGIN | |
NSString * const RingerSwitchDidChangedNotification = @"RingerSwitchDidChangedNotification"; | |
@interface RingerSwitchObserver () | |
@property (nonatomic, getter=isSlient) BOOL silent; | |
@end | |
@implementation RingerSwitchObserver | |
+ (instancetype)sharedObserver | |
{ | |
static dispatch_once_t onceToken; | |
static RingerSwitchObserver *sObserver; | |
dispatch_once(&onceToken, ^{ | |
sObserver = [[RingerSwitchObserver alloc] init]; | |
}); | |
return sObserver; | |
} | |
- (instancetype)init | |
{ | |
if (self = [super init]) { | |
int token; | |
if (notify_register_dispatch("com.apple.springboard.ringerstate", &token, dispatch_get_main_queue(), ^(int token) { | |
[self _updateSilentWithToken:token]; | |
}) == NOTIFY_STATUS_OK) { | |
[self _updateSilentWithToken:token]; | |
} else { | |
// Default to assume the ringer switch is ON. | |
_silent = YES; | |
} | |
} | |
return self; | |
} | |
- (void)_updateSilentWithToken:(int)token | |
{ | |
uint64_t state; | |
if (notify_get_state(token, &state) == NOTIFY_STATUS_OK) { | |
self.silent = (state == 0); | |
} else { | |
// Default to assume the ringer switch is ON. | |
self.silent = YES; | |
} | |
} | |
- (void)setSilent:(BOOL)silent | |
{ | |
if (_silent == silent) { | |
return; | |
} | |
_silent = silent; | |
[[NSNotificationCenter defaultCenter] postNotificationName:RingerSwitchDidChangedNotification object:self]; | |
} | |
@end | |
NS_ASSUME_NONNULL_END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment