【问题标题】:How to detect screen lock/unlock in iOS Swift 4?如何在 iOS Swift 4 中检测屏幕锁定/解锁?
【发布时间】:2018-01-17 04:04:47
【问题描述】:

如何在 iOS 中检测屏幕锁定/解锁? 我正在使用 Swift 4 (Xcode 9.2),我尝试了以下链接,但它们对我不起作用。

如果有人可以教我,我会很高兴。谢谢。

【问题讨论】:

    标签: ios swift iphone


    【解决方案1】:

    您可以通过在 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,我只是想知道这是否会得到 Apple 的批准。或者如果我使用这种方法来检测设备的锁定状态,我的申请会被拒绝吗?
    【解决方案2】:

    首先,我们需要为我们的应用注册锁定/解锁事件通知,为此我们将使用使用 c api 的 Objective C。

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

    【讨论】:

      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 2016-08-24
      • 2016-03-30
      • 2023-03-10
      相关资源
      最近更新 更多