Skip to content

Instantly share code, notes, and snippets.

@niw niw/RingerSwitchObserver.h
Last active Mar 14, 2019

Embed
What would you like to do?
Get current iPhone/iPad ringer switch (mute switch) state and change events
@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
#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
You can’t perform that action at this time.