我一直致力于企业iOS / Swift(iOS 11.3,Xcode 9.3.1)应用程序,我希望在屏幕更改(变为空白或变为活动状态)时收到通知,并在Realm数据库中捕获事件。我正在使用detect screen unlock events in IOS Swift中tbaranes的答案并且它有效,但是当屏幕变为空白并变为活动时,我发现添加了重复:
初始重新激活:记录两个事件
第二个空白:记录两个事件
第二次重演:记录三个事件
和每个周期添加额外事件的循环。
这必须是代码中的某些内容(或代码中缺少的)导致附加效果,但我无法找到它。并且,是的,print语句显示问题不在Realm数据库中,而是实际重复的语句。
我的代码如下。任何建议都表示赞赏。
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
Unmanaged.passUnretained(self).toOpaque(), // observer
displayStatusChangedCallback, // callback
"com.apple.springboard.hasBlankedScreen" as CFString, // event name
nil, // object
.deliverImmediately)
}
private let displayStatusChangedCallback: CFNotificationCallback = { _, cfObserver, cfName, _, _ in
guard let lockState = cfName?.rawValue as String? else {
return
}
let catcher = Unmanaged<AppDelegate>.fromOpaque(UnsafeRawPointer(OpaquePointer(cfObserver)!)).takeUnretainedValue()
catcher.displayStatusChanged(lockState)
print("how many times?")
}
private func displayStatusChanged(_ lockState: String) {
// the "com.apple.springboard.lockcomplete" notification will always come after the "com.apple.springboard.lockstate" notification
print("Darwin notification NAME = \(lockState)")
if lockState == "com.apple.springboard.hasBlankedScreen" {
print("A single Blank Screen")
let statusString = dbSource() // Realm database
statusString.infoString = "blanked screen"
print("statusString: \(statusString)")
statusString.save()
return
}