iOS Time change notification and previous time

2019-08-12 04:14发布

问题:

I have an application that works with timeout (let's say -> ring in 3 days). My problem occurs if a user change the device local time while being offline because I am comparing two NSDate (the final date and today) to check that timeout.

So I am trying to get notified when a user made a significant time change (several hours or days) in order to update my timers depending on the difference between before and after the update.

I found the UIApplicationSignificantTimeChangeNotification, which does :

Posted when there is a significant change in time, for example, change to a new day (midnight), carrier time update, and change to or from daylight savings time.

That nearly fits but I can't figure out how to get the "old" time in order to get the difference. I can't rely on a webserver neither because the app should be running in offline mode.

Any idea or suggest is welcome ;)

回答1:

I finally find a way to solve my problem by using the CPU time (which is always constantly increasing except on reboot).

First time the app is launched, I get the Real time and the CPU time.

Then, when I need to check if time has been changed, I just take

the Real time at first, I add to it ( the current CPU time - the CPU time at first).

This give me the correct time.

Note: take care to use the real CPU time, not the one used by timer because it's stop when device go to sleep.



回答2:

You should store the current time of your device, when your application goes into background. When the application comes into foreground, you should take the current time of your device. Now measure the difference between these 2 dates. If it is less than zero, it means, the user has set the device with previous date and you should throw the error of time out. If the difference is greater than 0, then you should compare current time with actual finish date.

One more indirect way is to start the location tracking of your device. Keep it on even when the app goes into background. When your didUpdateLocation delegate will hit by system, you will receive CLLocation object in argument. This location object is having currentTime details. Compare the time of last location and current location. If it is negative, user has bluffed with time. Its time to take the action.