How to handle time events on iOS?

2019-04-25 12:55发布

问题:

I'm coding an iPad app, and I have to change a graphic when the day changes to Sunday.

My straightforward solution is to check the day in the - (void)applicationDidBecomeActive:(UIApplication *)application or -(void)viewWillAppear:(BOOL)animated methods, and set a timer like every 10 mins to check if the day have changed to Sunday while the app is active.

Is there another, perhaps more efficient, way to handle this?

回答1:

In your appliciation delegate, implement the following method: -(void)applicationSignificantTimeChange:(UIApplication *)application

This method is called when the day changes, or if the device's time has been changed in the background for whatever reason (such as changes to time zone).



回答2:

Another option would be to use the same two methods you mentioned, "viewWillAppear:" and "applicationDidBecomeActive:" and instead of setting a timer for every 10 minutes, just calculate the amount of time between the current time and the next Sunday. Take that time interval and use it to set a timer that will fire exactly at midnight on Sunday.



回答3:

There's a notification for when the day changes. You could listen to it and check if it's sunday when it fires.

You should also check if it's sunday at launch.



回答4:

What's wrong with that solution? Does it become Sunday more frequently than once every 10 minutes in some places?

One thing you might want to consider: in your timer fire method, if the time is after 23:50 then reschedule the timer for sooner (i.e. around 00:00) so you're more likely to catch midnight accurately.



回答5:

This chapter might prove useful, using some type of Notification to update:

http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/IPhoneOSClientImp/IPhoneOSClientImp.html#//apple_ref/doc/uid/TP40008194-CH103-SW1

Although I myself ended up with the same solution you are using, it's just easier and more reliable I find.