简体   繁体   中英

how to tell when the device screen is locked or unlocked in swift

Essentially I have a timer in my app and I need it to keep running if the phone or device gets locked while the timer is active. After a whole lot of searching I found that's not really possible, or well it is, but doing so could violate apple developer guidelines and could get the app removed from the store.

So I thought I would get a little clever and create a property in my AppDelegate of Int64 for "timerStartedAt" which is just a Date().millisecondsSince1970 (custom extension I have)...

extension Date {
    var millisecondsSince1970: Int64 {
        return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
    }

    init(milliseconds: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }

}

Then in the "viewWillAppear" of my timer view controller I check that property and set the time has been running of now - that time. However, viewWillAppear doesn't get called when the screen is unlocked. It does get called if the user switches pages in the application, but not when the screen locks and then unlocks.

So I am trying to find a way to call a method in my view controller when the device gets unlocked. Is that even possible?

As the device is being locked, if your app was frontmost, then you'll get applicationWillResignActive(_:) in the app delegate, and the corresponding notification if you register for it.

As the device is being unlocked, if your app was frontmost, then it will be active and frontmost again and you'll get applicationDidBecomeActive in the app delegate, and the corresponding notification if you register for it.

(If your app was not frontmost, you have no way to detect that anything is happening, but that's okay because there is no "you" — the app is not running.)

That is sufficient to let you write a timer that "keeps counting" in the background by looking at the different between the time it started (or the time we deactivated) and the time when we are activated. So the timer effectively "runs" in the background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM