我使用以下代码检查iphone锁定状态。
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
}
});
问题是我们只有在设备被锁定或解锁时才会收到通知。我想知道当前的锁定状态。即。我已经启动了应用程序,在任何时候我想知道设备是锁定还是解锁。使用上述代码,我们只会在用户锁定或解锁设备时收到通知。
这有什么替代方案吗?
答案 0 :(得分:5)
参见
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);
}
此外,您可以设置Global bool变量并设置其值是否锁定设备。
答案 1 :(得分:2)
/**
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)
}