Tools & releasesHistorical technical note

Detecting device locking in an iOS app

Records SpringBoard lock-notification handling used to investigate a failure in an embedded game when the device locked. It preserves the troubleshooting approach and callback code; the conditions under which those interfaces may be used need separate verification.

Author:

Originally credited to Bison. Content is retained as published.

English translation of the Chinese original, translated on . The article body uses automated translation; app descriptions, historical reading notes and video subtitles receive separate editorial checks. Original publication dates, attribution, code and version notes are retained.

"Health is the foundation of everything. Getting more exercise is the way to go." Bison

A recent project contains an embedded game, and the app crashes as soon as the screen locks. I spent a long time looking for a solution.

The code is as follows

Core code

#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")

#define NotificationChange CFSTR("com.apple.springboard.lockstate")

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    
    [self lookLockScreen];

    return YES;
    
}

- (void)lookLockScreen
{
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationLock, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, screenLockStateChanged, NotificationChange, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);


}

static void screenLockStateChanged(CFNotificationCenterRef center,void* observer,CFStringRef name,const void* object,CFDictionaryRef userInfo)

{

    NSString* lockstate = (__bridge NSString*)name;

    if ([lockstate isEqualToString:(__bridge  NSString*)NotificationLock]) {

        //锁屏
        NSLog(@"locked.");

    } else {
        //锁屏状态改变
        NSLog(@"lock state changed.");

    }

}