Detect Screen Unlock Events in iOS Swift

React Native: How to detect device lock/unlock event?

Since that day I couldn't find any way to detect Lock/Unlock event in React native.

Solution:

  1. We've created sample modules in Android and iOS separate (Native code to get Lock/Unlock events)
  2. Using Android studio / XCode we've exported as React native modules
  3. Imported these modules in React native

It works fine for us.

Hope this would help you.

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

iOS: How to check if screen is locked when app is in background

When the screen is locked, your app gets these delegate messages:

  • applicationWillResignActive:

  • applicationDidEnterBackground:

However, you cannot distinguish this situation from any other situation in which you might get those messages (e.g., the user clicked the Home button to suspend your app).



Related Topics



Leave a reply



Submit