开发者

Fire a method ever 24 hours

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 开发者_StackOverflowideal 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).

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.

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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜