3

How can I detect screen lock/unlock in iOS? I am using Swift 4 (Xcode 9.2), and I have tried following links but they are not working for me.

I would be happy if someone can teach me. Thanks.

Anshul Bhatheja
  • 673
  • 3
  • 21
fabius
  • 57
  • 1
  • 2

2 Answers2

0

you can detect the screen lock/unlock by writing the following code in AppDelegate.m file:-

var notify_register_dispatch: int notify_token?
"com.apple.springboard.lockstate", notify_token, DispatchQueue.main
[uint64_t]
state = UINT64_MAX
notify_get_state(token, state)
if state == 0 {
    print("Unlocked")
}
else {
    print("Locked")
}

This code will help you to get the info regarding the screen lock/unlock in foreground

Swati Gautam
  • 191
  • 9
  • Hi Swati, I just wanted to know if this will be approved by Apple. Or will my application get rejected if I use this method to detect the lock state of device? – Parth Bhatt Mar 06 '20 at 08:23
0

First of all we need to register our app for lock/unlock events notification, for this we are going to use Objective C which uses c api.

DeviceLockStatus.m

#import "DeviceLockStatus.h"
#import "notify.h"
#import "YourProjectName-Swift.h"

@implementation DeviceLockStatus

-(void)registerAppforDetectLockState {
 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);

        DeviceStatus * myOb = [DeviceStatus new];  //DeviceStatus is .swift file

        if(state == 0) {
            myOb.unlocked;

        } else {
            myOb.locked;
        }

    });
}
@end

Here we have used three import statements. DeviceStatus.h as follows :

#ifndef DeviceLockStatus_h
#define DeviceLockStatus_h

#import  "foundation.h"
@interface DeviceLockStatus : NSObject

@property (strong, nonatomic) id someProperty;

-(void)registerAppforDetectLockState;

@end
#endif /* DeviceLockStatus_h */

In Swift Projects we need to use #import "DeviceLockStatus.h" in Bridging-Header.

"YourProjectName-Swift.h"

is used to used to call Swift methods from Objective C code, although this file is not visible but we need to import this file if we want to call swift methods from Objective C.

DeviceStatus.swift

import Foundation

 class DeviceStatus : NSObject {

     func locked(){
        print("device locked") // Handle Device Locked events here.
    }

     func unlocked(){
         print("device unlocked") //Handle Device Unlocked events here.
    }
}
Anand Verma
  • 572
  • 1
  • 6
  • 11