每24小时触发一种方法 [英] Fire a method ever 24 hours

查看:81
本文介绍了每24小时触发一种方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在给定时间每天触发一种方法.我已经尝试了一些方法,但无法真正使它起作用.任何意见,将不胜感激.另外,无论应用程序是否打开,它都会触发将是理想的选择.这可能吗?

I am trying to fire a method once a day at a given time. I've tried a few things but I can't really make it work. any advice would be appreciated. Also, it would be ideal if it would fire regardless of if the app is open or not. Is this possible?

推荐答案

UILocalNotification will let you fire a notification (but not a method) when your app is running in the background, or will call a delegate method you implement (application:didReceiveLocalNotification:) if the app is running in the foreground, or will call a method you must implement (application:didFinishLaunchingWithOptions:) when the user responds to the alert. Other than this, you will not be able to call a method when the app is not in the foreground, you will only be able to fire the the notification (which can display the badge, play a sound, etc).

顺便说一句,如果您要使用此功能,请考虑向Apple提交错误报告.我希望能够基于本地通知在后台运行方法,而不必等待用户首先响应.

By the way, consider filing a bug report with apple if this is a feature you want. I would like the ability to run methods in the background based on local notifications, without waiting for the user to respond first.

请参阅Apple的示例代码:

See Apple's example code:

- (void)scheduleNotificationWithItem:(ToDoItem *)item interval:(int)minutesBefore {
    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:item.day];
    [dateComps setMonth:item.month];
    [dateComps setYear:item.year];
    [dateComps setHour:item.hour];
    [dateComps setMinute:item.minute];
    NSDate *itemDate = [calendar dateFromComponents:dateComps];
    [dateComps release];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = [itemDate addTimeInterval:-(minutesBefore*60)];
    localNotif.timeZone = [NSTimeZone defaultTimeZone];

    localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"%@ in %i minutes.", nil),
         item.eventName, minutesBefore];
    localNotif.alertAction = NSLocalizedString(@"View Details", nil);

    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = 1;

    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:item.eventName forKey:ToDoItemKey];
    localNotif.userInfo = infoDict;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];
}

这篇关于每24小时触发一种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆