Skip to content

Instantly share code, notes, and snippets.

@immortalsantee
Last active January 20, 2021 21:11
Show Gist options
  • Save immortalsantee/1e0832c2ada68a2c8893ce9a0b8a1467 to your computer and use it in GitHub Desktop.
Save immortalsantee/1e0832c2ada68a2c8893ce9a0b8a1467 to your computer and use it in GitHub Desktop.
Device lock unlock state detection from today extension
weak var deviceUnlockedObserver: NSObjectProtocol?
weak var deviceLockedObserver: NSObjectProtocol?
var isDeviceLocked = true
private func addDeviceUnlockedObserver() {
guard deviceUnlockedObserver == nil else {return}
deviceUnlockedObserver = NotificationCenter.default.addObserver(forName: .UIApplicationProtectedDataDidBecomeAvailable, object: nil, queue: .main) { (noti) in
DispatchQueue.main.async {
self.isDeviceLocked = false
}
}
}
private func addDeviceLockedObserver() {
guard deviceLockedObserver == nil else {return}
deviceLockedObserver = NotificationCenter.default.addObserver(forName: .UIApplicationProtectedDataWillBecomeUnavailable, object: nil, queue: .main) { (noti) in
DispatchQueue.main.async {
self.isDeviceLocked = true
}
}
}
private func removeObserver() {
if let unlockObserver = deviceUnlockedObserver {
NotificationCenter.default.removeObserver(unlockObserver)
}
if let lockedObserver = deviceLockedObserver {
NotificationCenter.default.removeObserver(lockedObserver)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment