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