How can I detect screen lock/unlock events on the iPhone?

Vikas S Singh picture Vikas S Singh · Oct 25, 2011 · Viewed 30.3k times · Source

How can I detect screen lock/unlock events on the iPhone? When the user unlocks it, I want to show a notification alert from my iPhone app. (For Just like Broadcast Receiver for screen unlock in Android.)

Answer

Rohit Kashyap picture Rohit Kashyap · Jan 11, 2013

Check this out, I wanted to detect the lock/unlock events, I solved it by Darwin notifications. You can detect the event when the device is locked by "com.apple.springboard.lockcomplete".

//call back
static void displayStatusChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
    // the "com.apple.springboard.lockcomplete" notification will always come after the "com.apple.springboard.lockstate" notification

    NSString *lockState = (NSString*)name;
    NSLog(@"Darwin notification NAME = %@",name);

    if([lockState isEqualToString:@"com.apple.springboard.lockcomplete"])
    {
        NSLog(@"DEVICE LOCKED");
    }
    else
    {
        NSLog(@"LOCK STATUS CHANGED");
    }   
}


-(void)registerforDeviceLockNotif
{
    //Screen lock notifications
    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    NULL, // observer
                                    displayStatusChanged, // callback
                                    CFSTR("com.apple.springboard.lockcomplete"), // event name
                                    NULL, // object
                                    CFNotificationSuspensionBehaviorDeliverImmediately);

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
                                    NULL, // observer
                                    displayStatusChanged, // callback
                                    CFSTR("com.apple.springboard.lockstate"), // event name
                                    NULL, // object
                                    CFNotificationSuspensionBehaviorDeliverImmediately);  
}