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.
}
}