Sunday, July 13, 2014

How to detect screen lock/unlock events on the iPhone !

To solve it i use "Darwin Notifications". You can detect the event when device lock/unlock by "com.apple.springboard.lockcomplete"

Let's follow this code:

   

//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 = (__bridge NSString*)name;

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

  

    if([lockState isEqualToString:@"com.apple.springboard.lockcomplete"])

    {

        NSLog(@"DEVICE LOCKED");

    }

    else

    {

        NSLog(@"LOCK STATUS CHANGED");

    }

}





-(void)registerforDeviceLockNotification

{

    //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);



}

   

No comments:

Post a Comment