每天在特定时间呼叫方法

时间:2013-05-20 16:29:01

标签: ios nstimer

我的应用程序在自助服务终端模式下不断运行。在特定时间每24小时一次,我需要将核心数据中的一些数据同步到Web服务。

我知道如何进行同步,但我不知道如何安排应用程序在每天的特定时间进行同步通话,例如上午02:45。

当应用程序不断运行时,是否可以执行此类操作?

3 个答案:

答案 0 :(得分:4)

使用本地通知。这是一个教程:http://www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/

希望这有助于你开始...

这也是:

Local Notifications

Background Tasks

答案 1 :(得分:3)

感谢来自@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
} 

答案 2 :(得分:-2)

一个简单的解决方案就是将NSTimer设置为每分钟(或每秒)检查当前日期。如果当前日期大于所需日期,则触发该方法并更新所需日期。