Unable to consistently detect lock/unlock events with Swift

I need to detect lock & unlock events in my swift iOS application.

I have tried using AppDelegate functions like UIApplicationProtectedDataWillBecomeUnavailable & UIApplicationProtectedDataDidBecomeAvailable to record the lock and unlock events respectively, but have found this to be inconsistent.

UIApplicationProtectedDataWillBecomeUnavailable is not called immediately after the lock event, and sometimes misses the event altogether.

Is there a different approach to this problem that guarantees detecting lock & unlock correctly every time?

Protected data availability is related to, but not exactly the same as, screen lock. You wrote:

UIApplicationProtectedDataWillBecomeUnavailable is not called immediately after the lock event

Right. The system delays data protection for a while to give various components time to persist their state.

sometimes misses the event altogether.

I’d be very surprised if the events were missed altogether. However, there are ways you can run into problems here. For example:

  1. User locks screen.

  2. Your app moves to the background.

  3. Your app suspends before protected data becomes unavailable.

  4. Your app remains suspended.

  5. Eventually the system terminates your app to recover memory.

At that point your app has ‘missed’ the event.

I need to detect lock & unlock events in my swift iOS application.

Why? What are you doing in response to those events?

Share and Enjoy

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

Hi, thanks for the quick reply.

Your app suspends before protected data becomes unavailable.

The application that I mentioned is one that works actively in the background. This has been confirmed by looking into the other features of the app, and they are working as expected.

Why? What are you doing in response to those events?

The requirement of this application is to track how many times a user interacts with their phone when they are on a journey. Is there a way to detect these better?

Unable to consistently detect lock/unlock events with Swift
 
 
Q