'clock_get_time/mach_absolute_time stops updating when device goes to sleep on iOS 7

My application uses mach_absolute_time to calculate the ticks since the last touch event and logs the user out if it surpasses an idle time limit of 10 minutes.

This all works fine on iOS 6, but I noticed that it was not behaving correctly on iOS 7. Specifically, when the iOS 7 device is unplugged (on battery), it seems that the device stops incrementing its ticks once it goes to sleep following this line in the console (this happens after about 5 minutes of inactivity):

powerd[47] : Sleep: Using BATT (Charge:99%)

Therefore, when I wake the device up after 10 minutes, and calculate the ticks using mach_absolute_time, the difference shows to be only 5 minutes (when in reality, 10 minutes have passed).

Strangely enough, all works properly and the ticks continue to run when the device is plugged in to a power source. It never shows that the device is going to sleep on the console log when it is plugged in (although the screen does turn off and the behavior is the same visually as when unplugged).

I've tried this using clock_get_time as well, and I'm facing the same issue there.

Is there something I can do in iOS 7 to keep Mach absolute time ticking when the device goes to sleep? I don't want to use [[NSDate date] timeIntervalSince1970] as users are able to manipulate the system time and bypass this.

Thanks for any insights.



Solution 1:[1]

You can nowadays use clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) which includes the time spent asleep. In Swift:

import Foundation

let elapsed_time_nanos = clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW)

I can't find documentation for that function on the Apple website, but the docs for mach_continuous_time mention it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 robinst