最近刚开始学习用swift写一个小应用,由于应用需要区分锁屏和home键,上网查了许久,终于找到了方法。
我们需要在AppDelegate.swift中的func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool方法中添加一个监听CFNotificationCenterAddObserver(_center:CFNotificationCenter!,_observer:UnsafeRawPointer!,_callBack:CFNotificationCallback!,_name:CFString!,_object:UnsafeRawPointer!,_suspensionBehavior:CFNotificationSuspensionBehavior):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
observer,
{ (_, observer, _, _, _) -> () in
if let observer = observer { let mySelf = Unmanaged.fromOpaque(observer).takeUnretainedValue() mySelf.callback() } },
"com.apple.springboard.lockstate" as CFString,
nil,
CFNotificationSuspensionBehavior.deliverImmediately)
return true }
我们这个监听是基于Darwin层的监听CFNotificationCenterGetDarwinNotifyCenter(),当我们锁屏和解锁的时候,通知中心会广播一个消息"com.apple.springboard.lockstate",当我们监听到后,我们便会调用callBack方法,我尝试写过自定义的callBack方法,但是总有错误,于是尝试使用闭包,但由于闭包无法获取上下文,所以我通过callBack中的传参observer使用Unmanaged.fromOpaque(observer).takeUnretainedValue()获取self,至此便能调用AppDelegate中的方法
注意
由于ios11.0以后的版本监听锁屏键通知消息出现了修改,如下:
IOS11以前 锁屏时:hasBlankedScreen lockcomplete lockstate 开启屏幕未解锁:无通知消息 解锁时:hasBlankedScreen lockstate
IOS11以后 锁屏时:hasBlankedScreen 开启屏幕未解锁: lockcomplete (只执行一次) lockstate(只执行一次) hasBlankedScreen(每次开启屏幕都执行一次) 解锁时:lockstate
因此,由于iOS11以后的版本锁屏消息更改了所以要兼容ios11的锁屏键听则需要对当前ios版本进行判断,修改后的锁屏听的代码如下:
if #available(iOS 11.0, *) {
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer,{ (_, observer, _, _, _) -> () in
if let observer = observer {
let mySelf = Unmanaged<AppDelegate>.fromOpaque(observer).takeUnretainedValue()
mySelf.isSaveData = false
mySelf.callback()
}
}, "com.apple.springboard.lockstate" as CFString, nil, CFNotificationSuspensionBehavior.deliverImmediately)
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer,{ (_, observer, _, _, _) -> () in
if let observer = observer {
let mySelf = Unmanaged<AppDelegate>.fromOpaque(observer).takeUnretainedValue()
mySelf.isSaveData = true
mySelf.callback()
}
}, "com.apple.springboard.hasBlankedScreen" as CFString, nil, CFNotificationSuspensionBehavior.deliverImmediately)
} else {
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer,{ (_, observer, _, _, _) -> () in
if let observer = observer {
let mySelf = Unmanaged<AppDelegate>.fromOpaque(observer).takeUnretainedValue()
mySelf.callback()
}
}, "com.apple.springboard.lockstate" as CFString, nil, CFNotificationSuspensionBehavior.deliverImmediately)
}
总结
新手刚学,知识水平有限,如有错误之处,还望指出