每天在特定时间呼叫方法
我的应用程序在kiosk模式下不断运行。 在特定时间每24小时一次,我需要将核心数据中的一些数据同步到Web服务。
我知道如何进行同步,但我不知道如何安排应用程序在每天的特定时间进行同步呼叫,例如在凌晨02:45。
当应用程序不断运行时,是否可以执行此类操作?
使用本地通知。 这是一个教程: http : //www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
希望这有助于你开始……
这也是:
本地通知
后台任务
想出这个,感谢@lakesh的提示。 在它帮助某人的情况下发布解决方案,因为我发现NSNotification示例一开始很难理解。
在我的主视图控制器中,我添加了以下方法:
- (void)scheduleNotification { [[UIApplication sharedApplication] cancelAllLocalNotifications]; UILocalNotification *notif = [[UILocalNotification alloc] init]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [[NSDateComponents alloc] init]; components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]]; NSInteger day = [components day]; NSInteger month = [components month]; NSInteger year = [components year]; [components setDay: day]; [components setMonth: month]; [components setYear: year]; [components setHour: 02]; [components setMinute: 45]; [components setSecond: 0]; [calendar setTimeZone: [NSTimeZone systemTimeZone]]; NSDate *dateToFire = [calendar dateFromComponents:components]; notif.fireDate = dateToFire; notif.timeZone = [NSTimeZone systemTimeZone]; notif.repeatInterval = NSDayCalendarUnit; [[UIApplication sharedApplication] scheduleLocalNotification:notif]; }
这将在今天凌晨02:45设置今天通知的开火日期,并每天重复。
在我的视图控制器的viewDidLoad中,我调用上面的方法:
[self scheduleNotification];
在appdelegate中,我执行以下操作:
- (void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification { application.applicationIconBadgeNumber = 0; //call your method that you want to do something in your app }
一个简单的解决方案就是将NSTimer
设置为每分钟(或每秒)检查当前日期。 如果当前日期大于所需日期,则触发该方法并更新所需日期。