how to check if the iOS device is locked/unlocked using Swift?
如何使用Swift检测锁定/未锁定的iOS设备(例如Android中的SCRENON / SCREENOFF)
我使用以下方法创建相同的思想。
您需要使用桥接器将Objective C代码用于swift。
这里是用于在Objective c和Swift之间建立桥梁的链接。
完成后,您可以将以下.h文件添加到
然后将NotificationCenter.framework添加到您的项目中。
进入您的CustomObject.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #import"notify.h" -(void)registerAppforDetectLockState { 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) { NSLog(@"unlock device"); } else { NSLog(@"lock device"); } NSLog(@"com.apple.springboard.lockstate = %llu", state); UILocalNotification *notification = [[UILocalNotification alloc]init]; notification.repeatInterval = NSCalendarUnitDay; [notification setAlertBody:@"Hello world!! I come becoz you lock/unlock your device :)"]; notification.alertAction = @"View"; notification.alertAction = @"Yes"; [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]]; notification.soundName = UILocalNotificationDefaultSoundName; [notification setTimeZone:[NSTimeZone defaultTimeZone]]; [[UIApplication sharedApplication] presentLocalNotificationNow:notification]; }); } |
然后CustomObject.h
1 | -(void)registerAppforDetectLockState; |
现在进入快速代码,您可以直接使用此方法。
1 2 | var instanceOfCustomObject: LockViewController = LockViewController() instanceOfCustomObject.registerAppforDetectLockState(); |
希望这会有所帮助。