如何使用Swift检查iOS设备的锁定/解锁状态?

3

我如何使用Swift检测已锁定/未锁定的iOS设备(就像Android中的SCREENON / SCREENOFF)


如果您正在寻找一种不需要Objective-C / Bridging头文件的快速解决方案,请参考以下链接:https://dev59.com/9Zvga4cB1Zd3GeqPyC9m#42509825 - tbaranes
1个回答

5
我用以下方法创建相同的东西。
您需要使用桥接器将Objective C代码用于Swift。 这是创建Objective C到Swift之间桥接的链接。 完成后,您可以将以下.h文件添加到yourproject-Bridging-Header文件中,添加yourcontroller.h。
然后将NotificationCenter.framework添加到您的项目中。
在CustomObject.m中。
#import "notify.h"

-(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);

        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。
-(void)registerAppforDetectLockState;

现在你可以直接使用这个方法来编写 Swift 代码。
var instanceOfCustomObject: LockViewController = LockViewController()
instanceOfCustomObject.registerAppforDetectLockState();

希望这能帮上很多忙。


谢谢@Nimit Parekh,我已经成功让日志工作了。新的问题是,我们如何在使用Swift代码检测到日志时执行某些操作? :) - the_one
现在使用这个私有字符串会导致拒绝,需要考虑替代方案。 - Rhythmic Fistman
@RhythmicFistman,你有没有其他的替代方法?因为上面的答案现在已经不能再使用了。 - Nimit Parekh
你可以使用检测进入后台的方法来替换。UIApplicationDidEnterBackgroundNotification 进入后台和锁屏有一定的相关性。 - Rhythmic Fistman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接