如何在iOS中检测屏幕锁定/解锁?
我正在使用Swift 4(Xcode 9.2),我已经尝试了以下链接,但它们对我没有用。
如果有人能教我,我会很高兴。谢谢。
您可以通过在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")
}
这段代码将帮助您获取前台屏幕锁定/解锁的信息
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 */
"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.
}
}