Detecting iPhone lock and unlock when app is in the background

Hi,


Is there a way to detect iPhone lock and unlock events from an iOS application when the app itself is in the background.

Currently it looks like we can only detect screen lock/unlock when the app is in the foreground.


Please let us know if this is possible with the latest iOS version.

Replies

Currently it looks like we can only detect screen lock/unlock when the app is in the foreground.

How are you doing this?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Hey,


I have the same question, i use this code in Objective C :


int notify_token;
    notify_register_dispatch("com.apple.springboard.lockstate", &notify_token,dispatch_get_main_queue(), ^(int token) {
        uint64_t state = UINT64_MAX;
        notify_get_state(token, &state);
      
        /
      
        if(state == 0) {
            NSLog(@"Unlocked");
            /
          
        } else {
            NSLog(@"Locked");
            /
        }
      
    });


I launch it in my AppDelegate didFinishLaunchingWithOptions method.


In foreground the detection works perfectly but when the app is in background it doesn't work anymore. Any idea on how to make this work in background ?

i use this code in Objective C :

This notify key is not considered API. Apple’s general rule with stringly typed APIs is that you must only use Apple keys if they are explicitly documented. In the case of the Darwin notifications API, this means the key must be listed in

<notify_keys.h>
. As this key is not listed there, you mustn’t use it.

AFAIK there’s no public API for determine the screen lock state of the device. [You can be notified of data protection state changes, via

UIApplicationProtectedDataWillBecomeUnavailable
and
UIApplicationProtectedDataDidBecomeAvailable
, but that’s a different thing.]

Any idea on how to make this work in background ?

The Darwin notifications API will not resume (or relaunch) your process if it’s suspended (or terminated) when the notification is triggered. There’s no general way to do that.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thanks for your answer.


UIApplicationProtectData is working fine but it's not exactly what i'm looking for, i need more precision.


Do you know if there is a way to check if the user is using his phone while my app is in background ? For exemple he's on his message or email ?


Thanks.

Do you know if there is a way to check if the user is using his phone while my app is in background ?

Not in general.

For exemple he's on his message or email ?

And definitely not in this case. There have been hack-ish ways to do this in the past but they generally get closed off by the sandbox as a privacy bug.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

It will work Background and foreground also


Write this code in AppDelegate didFinishLaunchingWithOptions Method:

self.backgroundTaskIdentifier =

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{


[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];

}];

[self registerAppforDetectLockState];

-------------------------------------------------------

-(void)registerAppforDetectLockState {


/

notify_register_dispatch("com.apple.springboard.lockstate", &notify_token,dispatch_get_main_queue(), ^(int token) {

uint64_t state = UINT64_MAX;

notify_get_state(token, &state);

if(state == 0) {

NSLog(@"unlock device");

} else {

NSLog(@"lock device");

}

NSLog(@"com.apple.springboard.lockstate = %llu", state);

UILocalNotification *notification = [[UILocalNotification alloc]init];

notification.repeatInterval = NSCalendarUnitDay;/

[notification setAlertBody:@"Hello world!! I come becoz you lock/unlock your device :)"];

notification.alertAction = @"View";

notification.alertAction = @"Yes";

[notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];

notification.soundName = UILocalNotificationDefaultSoundName;

[notification setTimeZone:[NSTimeZone defaultTimeZone]];

[[UIApplication sharedApplication] presentLocalNotificationNow:notification];

});

}

@gupta163 and other folks, please stop advising people to use undocumented notification keys. As I discussed in my 23 Jan 2017 post, any notification key that’s not explicitly documented by Apple is considered private API.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Using protectedDataWillBecomeUnavailableNotification solved partially the problem as this notification does not always arrive in time as soon as the device is locked. Observing didEnterBackgroundNotification and willEnterForegroundNotification to request/terminate background execution time solved the notification delivery problem. In addition verifying that applicationState == .background in protectedDataWillBecomeUnavailableNotification makes it more stable.

This notify key is not considered API. Apple’s general rule with stringly typed APIs is that you must only use Apple keys if they are explicitly documented.


Where exactly are them documented?