美文网首页
iOS 检测屏幕是否锁定 🔓 / 🔒

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

作者: 煮石散人 | 来源:发表于2018-04-20 15:13 被阅读19次

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

相关文章

网友评论

      本文标题:iOS 检测屏幕是否锁定 🔓 / 🔒

      本文链接:https://www.haomeiwen.com/subject/yktzkftx.html