How can i detect screen unlock events on iPhone? When the user unlocks it, I want to perform an action in my app. I searched on googled but only found code related to object
I just updated the Code
just call the registerforDeviceLockNotification() function into app delegate didfinishLunch function (AppDelegate.swift)
if you are using session then call the registerforDeviceLockNotification() function into willConnectTo (SceneDelegate.swift)
example code (AppDelegate.swift)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerforDeviceLockNotification()
return true
}
func registerforDeviceLockNotification() {
//Screen lock notifications
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
Unmanaged.passUnretained(self).toOpaque(), // observer
displayStatusChangedCallback, // callback
"com.apple.springboard.lockcomplete" as CFString, // event name
nil, // object
.deliverImmediately)
}
private let displayStatusChangedCallback: CFNotificationCallback = { _, cfObserver, cfName, _, _ in
guard let lockState = cfName?.rawValue as String? else {return}
if (lockState == "com.apple.springboard.lockcomplete") {
print("DEVICE LOCKED")
} else {
print("LOCK STATUS CHANGED")
}
}
Example Code (SceneDelegate.swift)
func registerforDeviceLockNotification() {
//Screen lock notifications
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
Unmanaged.passUnretained(self).toOpaque(), // observer
displayStatusChangedCallback, // callback
"com.apple.springboard.lockcomplete" as CFString, // event name
nil, // object
.deliverImmediately)
}
private let displayStatusChangedCallback: CFNotificationCallback = { _, cfObserver, cfName, _, _ in
guard let lockState = cfName?.rawValue as String? else {return}
if (lockState == "com.apple.springboard.lockcomplete") {
print("DEVICE LOCKED")
} else {
print("LOCK STATUS CHANGED")
}
}