如何在iOS Swift 4中检测屏幕锁定/解锁?

3
2个回答

0

您可以通过在AppDelegate.m文件中编写以下代码来检测屏幕锁定/解锁:

var notify_register_dispatch: int notify_token?
"com.apple.springboard.lockstate", notify_token, DispatchQueue.main
[uint64_t]
state = UINT64_MAX
notify_get_state(token, state)
if state == 0 {
    print("Unlocked")
}
else {
    print("Locked")
}

这段代码将帮助您获取前台屏幕锁定/解锁的信息


嗨Swati,我只是想知道这个方法是否会被苹果批准。如果我使用这种方法来检测设备的锁定状态,我的应用程序会被拒绝吗? - Parth Bhatt

0
首先,我们需要为锁定/解锁事件通知注册我们的应用程序,为此我们将使用Objective C,它使用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

在这里,我们使用了三个导入语句。 DeviceStatus.h 如下:

#ifndef DeviceLockStatus_h
#define DeviceLockStatus_h

#import  "foundation.h"
@interface DeviceLockStatus : NSObject

@property (strong, nonatomic) id someProperty;

-(void)registerAppforDetectLockState;

@end
#endif /* DeviceLockStatus_h */

在 Swift 项目中,我们需要在 Bridging-Header 中使用 #import "DeviceLockStatus.h"。
"YourProjectName-Swift.h"

用于从Objective C代码中调用Swift方法的文件,虽然该文件不可见,但如果我们想要从Objective C中调用Swift方法,则需要导入此文件。

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.
    }
}

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