How can I fire a UILocalNotification for every 15 days with repeat interval in objc

696 views Asked by At

I am trying to fire an uilocalnotification for every 15 with repeated intervals at 6 AM in the morning.

i have tried a sample code, but not sure how to test it in simulator.

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:6];
[components setMinute:0];
[components setSecond:0];

// Gives us today's date but at 6am
NSDate *next6am = [calendar dateFromComponents:components];
NSLog(@"next9am BEFORE :%@",next6am);

if ([next6am timeIntervalSinceNow] < 0) {
    // If today's 6am already occurred, add 24hours to get to tomorrow's
    next6am = [next6am dateByAddingTimeInterval:60*60*24*15];
}

UILocalNotification* Localnotification = [[UILocalNotification alloc]init];

Localnotification.fireDate = next6am;
Localnotification.alertBody = @“it is been 15 days“;

Localnotification.repeatInterval = NSCalendarUnitWeekOfYear*2+NSCalendarUnitDay;
[[UIApplication sharedApplication] scheduleLocalNotification:Localnotification];

but not sure how to test it in simulator and not sure it will work help will be appreciated.

Thanks

3

There are 3 answers

0
D Madhu Kiran Raju On BEST ANSWER

After lot of searching over the internet and trying work around , i came to know that iOS repeat interval are as follows,

    NSCalendarUnitYear  // for every year              
    NSCalendarUnitMonth  // for every month          
    NSCalendarUnitDay     // for every day          
    NSCalendarUnitHour     // for every hour          
    NSCalendarUnitMinute  // for every minute
  and many more

We can set the repeat interval in the above fashion only.

But if we want to repeat interval for every 15 days we need to write an custom repeat interval for UILocalNotification .

so every year has 12 months and the number of event to be scheduled is 24 so i made loop for 2 years(730 days) and scheduled 48 event for the next 2 years

the below is the code for achieving the result

       UILocalNotification* Localnotification = [[UILocalNotification alloc]init];

       NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ;
        NSDateComponents *components =
        [calendar components:(NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit ) fromDate:[NSDate date]];

        [components setHour:6];
        [components setMinute:0];
        [components setSecond:0];
        // Gives us today's date
        NSDate *next6am = [calendar dateFromComponents:components];

        /*
         * Since every year has 365 days and
         */
        for (int i = 0; i<48; i++)//
        {
            next6am = [next6am dateByAddingTimeInterval:60*60*24*15];


            Localnotification.fireDate = next6am;

            //////add the userinfo for uilocal notification only after fire date. if called before the user info will not be updated.

            NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"15DaysAlerts"] forKey:@"notify"];
            Localnotification.userInfo = infoDict;

            if (CHECK_IOS_VERSION>8.2)
            {
                Localnotification.alertTitle = @"eKinCare";
            }
            Localnotification.alertBody = @"Any new medical reports to save?Touch to securely save & access anywhere, anytime.";
            // Set a repeat interval to monthly
            Localnotification.repeatInterval = NSCalendarUnitYear;
            [[UIApplication sharedApplication] scheduleLocalNotification: Localnotification];
            NSLog(@"next9am:%@",next6am);
        }

You can see all the scheduled events with this below method

-(void)showScheduledNotifications
{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *eventArray = [app scheduledLocalNotifications];
    NSLog(@"Events array : %@",eventArray);
    int scheduled_15daysAlerts = 0;

    for (int i=0; i<[eventArray count]; i++)
    {
        UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
        NSDictionary *userInfoCurrent = oneEvent.userInfo;
        NSString *uid=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:@"notify"]];
        if ([uid isEqualToString:@"15DaysAlerts"])
        {
            scheduled_15daysAlerts++;
            NSLog(@"yes found");
            //Cancelling local notification
        }
    }

    NSLog(@"Scheduled 15 days alert = [%d]",scheduled_15daysAlerts);
}

Hope this could help some one who are looking for a solution :)

1
Akshay Karanth On

local notifications work with the simulator. However, make sure you are implementing application:didreceiveLocalNotification in your app delegate if you want to see the nofication while your app is in the foreground:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"MyAlertView" message:notification.alertBody delegate:self cancelButtonTitle:@"OK"
        otherButtonTitles:nil];
    [alertView show];
    if (alertView) {
        [alertView release];
    }
}
0
Arnab On

In iOS 10, you can use UNTimeIntervalNotificationTrigger to schedule notification for every 15 days and repeat (set repeats: YES).

UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:(15*24*3600) repeats: YES];
NSLog(@"td %@", trigger.nextTriggerDate);

UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];

[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    if (error != nil) {
        NSLog(@"Something went wrong: %@",error);
    } else {
        NSLog(@"Created! --> %@",request);
    }
}];

Hope this will help anyone looking for this topic.