【发布时间】:2017-02-07 10:09:09
【问题描述】:
如何检测 iPhone 上的屏幕解锁事件?当用户解锁它时,我想在我的应用程序中执行一个操作。我在谷歌上搜索但只找到与目标 C 相关的代码,将其更改为 swift 但它不起作用。
关注这个博客:
http://kidtechblogs.blogspot.com/2014/07/how-to-detect-screen-lockunlock-events.html.
任何帮助我如何快速检测到它。
下面是改成swift的代码..
func displayStatusChanged(center: CFNotificationCenter, observer: Void, name: CFString, object: Void, userInfo: CFDictionaryRef) {
// the "com.apple.springboard.lockcomplete" notification will always come after the "com.apple.springboard.lockstate" notification
let lockState = (name as String)
print("Darwin notification NAME = \(name)")
if (lockState == "com.apple.springboard.lockcomplete") {
print("DEVICE LOCKED")
}
else {
print("LOCK STATUS CHANGED")
}
}
func registerforDeviceLockNotification() {
//Screen lock notifications
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
nil, // observer
displayStatusChanged, // callback
CFSTR("com.apple.springboard.lockcomplete"), // event name
nil, // object
.deliverImmediately)
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
nil, // observer
displayStatusChanged, // callback
CFSTR("com.apple.springboard.lockstate"), // event name
nil, // object
.deliverImmediately)
}
【问题讨论】:
-
当应用程序在前台时,darwin 通知是否有效?
-
此代码无效。
-
首先,您的方法 displayStatusChanged 假设是静态的。请检查一下。