Detect iPhone unlock / lock

I am trying to create an iOS app where I need to immediately know when the iPhone is unlocked. Let's say I want to print a log on the Xcode console whenever the phone is unlocked. From my app, how do I detect if the phone is unlocked? Some code pointers will be highly appreciated. I am a newbie in iOS/APP development. It should work even if my app is not running. Is it even possible to do so?

Replies

I need to immediately know when the iPhone is unlocked.

Why? Can you detail what app functionality depends on this?

There’s no specific notification for unlocking, but take a look at app delegate method applicationProtectedDataDidBecomeAvailable(_:) (link) and corresponding notification protectedDataDidBecomeAvailableNotification (link).

I am a newbie in iOS/APP development.

Welcome! You’ll find that Apple APIs tend not to just give you random information about the system (“is the device locked?”) but instead support more specific use cases like the delegate and notification given above: “can I access protected data right now?”

It should work even if my app is not running.

There are various events that can wake or launch your app (see LaunchOptionsKey at link) but unlocking isn’t one of them.

Thanks for a quick reply @Scott. I am trying to write a tiny app where I want to track how many times a device has been unlocked in a day / Week / Month. The app will mostly be in a closed state. It will only need to count the number of unlocks and store it. What could be the best approach to do this? Is this data readily available somewhere?

What could be the best approach to do this?

I don’t see any way to do that programmatically because…

The app will mostly be in a closed state.

For this to work the system would have to resume (or relaunch) your app in the background every time the device is unlocked, and there’s no facility to do that.

The only other way to achieve this would be for the system to main these metrics for you, and give you access to them via some API. Again, there’s no API for that.

Are you targeting a managed environment? Or do you expect to ship this on the App Store for general users?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"