How to detect device Lock Unlock status in iOS
Posted By : Varun Wadhwa | 12-Jun-2016
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. } }
Thanks,
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Varun Wadhwa
Varun is a mobile developer with experience in various technologies like Titanium , Cordova and native iOS development.