iOS 检测屏幕是否锁定 🔓 / 🔒

1. 导入头文件

#import <notify.h>

2. 给 CFNotificationCenter 添加观察者

- (void)addLockStatusObserver {
    CFNotificationCenterAddObserver(
                                    CFNotificationCenterGetDarwinNotifyCenter(),
                                    NULL,
                                    onLockStatusChange,
                                    LockStatusChangeNotiName,
                                    NULL,
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
    CFNotificationCenterAddObserver(
                                    CFNotificationCenterGetDarwinNotifyCenter(),
                                    NULL,
                                    onLockStatusChange,
                                    LockStatusLockedNotiName,
                                    NULL,
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
}

通知触发的回调 CFNotificationCallback :

void onLockStatusChange(
                        CFNotificationCenterRef center,
                        void *observer,
                        CFStringRef name,
                        const void *object,
                        CFDictionaryRef userInfo) {
    NSString *notiName = (__bridge NSString *)(name);
    if ([notiName isEqualToString:@"com.apple.springboard.lockstate"]) {
        // 无论锁定还是解锁,都会触发。锁定时,在 `lockcomplete` 之前触发
        NSLog(@"屏幕锁状态改变");
    } else if ([notiName isEqualToString:@"com.apple.springboard.lockcomplete"]) {
        // 锁定时触发
        NSLog(@"屏幕锁定");
    }
}

3. 别忘记移除观察者了

- (void)removeLockStatusOberser {
    CFNotificationCenterRemoveObserver(
                                       CFNotificationCenterGetDarwinNotifyCenter(),
                                       NULL,
                                       LockStatusChangeNotiName,
                                       NULL);
    CFNotificationCenterRemoveObserver(
                                       CFNotificationCenterGetDarwinNotifyCenter(),
                                       NULL,
                                       LockStatusLockedNotiName,
                                       NULL);
}

进一步了解:

官方文档 CFNotificationCenter

转载请注明出处: http://www.cnblogs.com/0xa6a

posted @ 2018-04-17 18:55 0xa6a 阅读(...) 评论(...) 编辑 收藏