Reputation: 149
I use the following code to check iphone lock state.
int notify_token;
notify_register_dispatch("com.apple.springboard.lockstate", ¬ify_token,dispatch_get_main_queue(), ^(int token) {
uint64_t state = UINT64_MAX;
notify_get_state(token, &state);
if (state == 0)
{
// Locked
}
else
{
// Unlocked
}
});
The problem is that we get notification only if device is locked or unlocked. I want to know the current lock status. ie. I have started the app and at any point of time I want to know whether device is locked or unlocked. Using the above code we will be notified only when device is locked or unlocked by the user.
Is there any alternatives for this?
Upvotes: 3
Views: 6755
Reputation: 8407
Swift:
/**
Start listen "Device Locked" notifications
*/
func registerforDeviceLockNotif() {
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
nil,
{(center: CFNotificationCenter!, observer: UnsafeMutablePointer<Void>, name: CFString!, object: UnsafePointer<Void>, userInfo: CFDictionary!) -> Void in
// the "com.apple.springboard.lockcomplete" notification will always come after the "com.apple.springboard.lockstate" notification
let lockState = name as String
if lockState == "com.apple.springboard.lockcomplete" {
NSLog("DEVICE LOCKED");
}
else {
NSLog("LOCK STATUS CHANGED");
}
},
"com.apple.springboard.lockcomplete",
nil,
CFNotificationSuspensionBehavior.DeliverImmediately)
}
Upvotes: 2
Reputation: 1324
Refer
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);
}
Moreover you can set Global bool variable and set its value whether device is locked or not.
Upvotes: 5