Trigger a method in background in iOS at a particular time

482 views Asked by At

Case: If your set a time 8:00 am and Days as Monday and Wednesday, then we notify the user at 8:00 am Monday and Wednesday. What are the best ways to handle this situation.

So far i searched, UILocalNotofication and NSTimer. Other that these things to handle?

2

There are 2 answers

1
Black Sheep On

This Apple example on how to do it with UILocalNotification

- (void)scheduleAlarmForDate:(NSDate*)theDate
{
    UIApplication* app = [UIApplication sharedApplication];
    NSArray*    oldNotifications = [app scheduledLocalNotifications];

    // Clear out the old notification before scheduling a new one.
    if ([oldNotifications count] > 0)
        [app cancelAllLocalNotifications];

    // Create a new notification.
    UILocalNotification* alarm = [[UILocalNotification alloc] init];
    if (alarm)
    {
        alarm.fireDate = theDate;
        alarm.timeZone = [NSTimeZone defaultTimeZone];
        alarm.repeatInterval = 0;
        alarm.soundName = @"alarmsound.caf";
        alarm.alertBody = @"Time to wake up!";

        [app scheduleLocalNotification:alarm];
    }
}

Apple doesn't let you run NSTimers on the background (There were some security issues), This Apple Guide that explains how to run tasks in the background and have some code examples like the one above.

0
agy On

I have read about other way to set alarms in this blog

Otherwise, I think you will have to use notifications.

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit|  NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];
[componentsForFireDate setWeekday: 2] ; 
[componentsForFireDate setHour: 8] ; 
[componentsForFireDate setMinute:0] ;
[componentsForFireDate setSecond:0] ;

NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];
UILocalNotification *notification = [[UILocalNotification alloc]  init] ;
notification.fireDate = fireDateOfNotification ;
notification.timeZone = [NSTimeZone localTimeZone] ;
notification.alertBody = [NSString stringWithFormat: @"Hi!"] ;
notification.userInfo= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Updates added for that week!"] forKey:@"subtitle"];
notification.repeatInterval= NSWeekCalendarUnit ;
notification.soundName=UILocalNotificationDefaultSoundName;


[[UIApplication sharedApplication] scheduleLocalNotification:notification] ;