Internal clock in iPhone background mode

后端 未结 5 1653
挽巷
挽巷 2020-12-10 08:37

In my application i want to run an internal clock in background mode [while application is not running in foreground].

The whole functionality will be like this:

5条回答
  •  無奈伤痛
    2020-12-10 08:58

    Update: Sorry to say my original answer isn't correct. When the device goes to sleep (can happen sometime after it's locked) the internal CPU clock stops ticking, and mach_absolute_time won't update either. Theoretically it will return the exact same value if you call it right before the device went to sleep, and after it awakes.

    The best available way I know of to check for date changes is kern.boottime, it holds the boot time, and is modified whenever the system time changes. Among other things, kern.boottime will be updated if the user changes the time, or if the OS changes the time itself according to info from cell towers.

    So, in your case, you can take the original time you calculated and modify it according to the modifications in kern.boottime. If you see kern.boottime changed significantly, it may mean that the device was turned off, and in this case you will need to contact the server to ask it for the time until the flight.

    Relevant code:

    time_t getBootTimeSecs(void)
    {
        struct timeval boottime;    
        size_t size = sizeof(boottime);
        int ret = sysctlbyname("kern.boottime", &boottime, &size, NULL, 0);
        assert(ret == 0);
        return boottime.tv_sec;
    }
    

    Original (incorrect) answer: You can use mach_absolute_time which isn't affected by date changes made by the user.

    When you book the ticket, get the correct date from the server and record mach_absolute_time. Now you will always be able to call mach_absolute_time whenever you want, calculate the difference from the one you recorded initially, and display the correct date.

    This will only work as long as the device wasn't shut down, in that case it makes sense for the app to re-connect to the server to get the correct date.

    You can also either Local or Push Notifications to alert the user when the target date is getting closer, even if the app isn't running.

提交回复
热议问题