How to Check If the iOS Device Is Locked/Unlocked Using Swift

how to tell when the device screen is locked or unlocked in swift

As the device is being locked, if your app was frontmost, then you'll get applicationWillResignActive(_:) in the app delegate, and the corresponding notification if you register for it.

As the device is being unlocked, if your app was frontmost, then it will be active and frontmost again and you'll get applicationDidBecomeActive in the app delegate, and the corresponding notification if you register for it.

(If your app was not frontmost, you have no way to detect that anything is happening, but that's okay because there is no "you" — the app is not running.)

That is sufficient to let you write a timer that "keeps counting" in the background by looking at the different between the time it started (or the time we deactivated) and the time when we are activated. So the timer effectively "runs" in the background.

Is there a way to check if the iOS device is locked/unlocked?

I solved it like this:

//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
CFStringRef nameCFString = (CFStringRef)name;
NSString *lockState = (NSString*)nameCFString;
NSLog(@"Darwin notification NAME = %@",name);

if([lockState isEqualToString:@"com.apple.springboard.lockcomplete"])
{
NSLog(@"DEVICE LOCKED");
//Logic to disable the GPS
}
else
{
NSLog(@"LOCK STATUS CHANGED");
//Logic to enable the GPS
}
}

-(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);
}

Note: the "com.apple.springboard.lockcomplete" notification will always come after the "com.apple.springboard.lockstate" notification

Update

The order of the two notifications can no longer be relied upon, as of recent versions of iOS



Related Topics



Leave a reply



Submit