How to set Local Notification repeat interval to custom time interval?

52,173

Solution 1

Got the answer, it is as straight as it gets.

You cannot create custom repeat intervals.

You have to use on NSCalendarUnit's in-built Unit Time Intervals.

I tried all the above solutions and even tried other stuffs, but neither of them worked.

I have invested ample time in finding out that there is no way we can get it to work for custom time intervals.

Solution 2

The repeat interval is just an enum that has a bit-map constant, so there is no way to have custom repeatIntervals, just every minute, every second, every week, etc.

That being said, there is no reason your user should have to set each one. If you let them set two values in your user interface, something like "Frequency unit: Yearly/Monthly/Weekly/Hourly" and "Every ____ years/months/weeks/hours" then you can automatically generate the appropriate notifications by setting the appropriate fire date without a repeat.

UILocalNotification *locNot = [[UILocalNotification alloc] init];
NSDate *now = [NSDate date];
NSInterval interval;
switch( freqFlag ) {     // Where freqFlag is NSHourCalendarUnit for example
    case NSHourCalendarUnit:
        interval = 60 * 60;  // One hour in seconds
        break;
    case NSDayCalendarUnit:
        interval = 24 * 60 * 60; // One day in seconds
        break;
}
if( every == 1 ) {
    locNot.fireDate = [NSDate dateWithTimeInterval: interval fromDate: now];
    locNot.repeatInterval = freqFlag;
    [[UIApplication sharedApplication] scheduleLocalNotification: locNot];
} else {
    for( int i = 1; i <= repeatCountDesired; ++i ) {
        locNot.fireDate = [NSDate dateWithTimeInterval: interval*i fromDate: now];
        [[UIApplication sharedApplication] scheduleLocalNotification: locNot];
    }
}
[locNot release];

Solution 3

I have one idea how to do this, i've implemented this in my project

First, create local notification with fire date (for example, every minute). Next step - fill user info with unique id for this notification (if you want to remove it in future) and your custom period like this:

-(void) createLocalRepeatedNotificationWithId: (NSString*) Id
{

    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    NSTimeInterval your_custom_fire_interval = 60; // interval in seconds
    NSDate *remindDate = [[NSDate date] dateByAddingTimeInterval:your_custom_fire_interval];
    localNotification.fireDate = remindDate;
    localNotification.userInfo = @{@"uid":Id, @"period": [NSNumber numberWithInteger:your_custom_fire_interval]};
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

After that, implement -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification in your AppDelegate:

  1. Fetch your custom period from user info.
  2. Change fire date for next period
  3. Just add it into the sheluded notificatiots again!

    NSInteger period = [[notification.userInfo objectForKey:@"period"] integerValue]; //1
    NSTimeInterval t= 10 * period;
    notification.fireDate =[[NSDate date] dateByAddingTimeInterval:t]; //2 
     [[UIApplication sharedApplication] scheduleLocalNotification:notification]; //3
    

if you want to remove this notification, do

UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
    UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
    NSDictionary *userInfoCurrent = oneEvent.userInfo;
    NSString *uid=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:@"id"]];
    if ([uid isEqualToString:notification_id_to_remove])
    {
        //Cancelling local notification
        [app cancelLocalNotification:oneEvent];
        break;
    }
}

Very important!

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification do not called, when you at background. So, you must setup long-running background task, where you will create notification again.

Solution 4

i have used this code and it is working fine for repeat LocalNotification i have used LavaSlider Code for this code implemetation

     UILocalNotification *    localNotifEndCycle = [[UILocalNotification alloc] init];
      localNotifEndCycle.alertBody = @"Your Expected Date ";
      NSDate *now = [NSDate date];

      for( int i = 1; i <= 10;i++) 
     {
        localNotifEndCycle.alertBody = @"Your Expected Date ";
        localNotifEndCycle.soundName=@"best_guitar_tone.mp3";
        localNotifEndCycle.fireDate = [NSDate dateWithTimeInterval:180*i sinceDate:now];
        [[UIApplication sharedApplication] scheduleLocalNotification: localNotifEndCycle];
     }
     }

Solution 5

-(void)schedulenotificationfortimeinterval:(NSString *)id1
{
    NSLog(@"selected value %d",selectedvalue);

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MMM dd,yyyy hh:mm a"];

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


   // localNotification2. fireDate = [[formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] dateByAddingTimeInterval:0];

    if(selectedvalue==0)
    {
        NSLog(@"dk 0000");

        localNotification2.fireDate = [formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] ;//now

        localNotification2.applicationIconBadgeNumber = 1;

        localNotification2.repeatInterval=NSDayCalendarUnit;

    }
    if(selectedvalue==1)
    {
        NSLog(@"dk 1111");

        for( int u = 0; u <= 2 ;u++)
        {
        localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] dateByAddingTimeInterval:43200.0*u] ;// 12 hr 
            localNotification2.repeatInterval=NSDayCalendarUnit;

            localNotification2.alertBody = [NSString stringWithFormat:@"Friendly reminder to take %@ %@ at %@.",[MedicationDict objectForKey:@"DrugName"],[MedicationDict objectForKey:@"Frequency"],[MedicationDict objectForKey:@"Ending"]];

            localNotification2.alertAction = @"Notification";
            localNotification2.soundName=UILocalNotificationDefaultSoundName;
            localNotification2.applicationIconBadgeNumber = 2;


            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];

            NSLog(@"all notifications %@",[[UIApplication sharedApplication]scheduledLocalNotifications]);

        }

     //  localNotification2.repeatInterval=NSDayCalendarUnit;

     }

    if(selectedvalue==2)
    {
        NSLog(@"dk 22222");
        for( int u = 0; u <= 3 ;u++)
        {
            localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] dateByAddingTimeInterval:28800.0*u] ;//8 hr 
            localNotification2.repeatInterval=NSDayCalendarUnit;

            localNotification2.alertBody = [NSString stringWithFormat:@"Friendly reminder to take %@ %@ at %@.",[MedicationDict objectForKey:@"DrugName"],[MedicationDict objectForKey:@"Frequency"],[MedicationDict objectForKey:@"Ending"]];

            localNotification2.alertAction = @"Notification";
            localNotification2.soundName=UILocalNotificationDefaultSoundName;
            localNotification2.applicationIconBadgeNumber = 3;


            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];

            NSLog(@"all notifications %@",[[UIApplication sharedApplication]scheduledLocalNotifications]);

        }


      //  localNotification2.repeatInterval=NSDayCalendarUnit;
    }

    if(selectedvalue==3)
    {
       NSLog(@"dk 3333");
        for( int u = 0; u <= 4 ;u++)
        {
            localNotification2.fireDate = [[formatter dateFromString:[NSString stringWithFormat:@"%@ %@",[MedicationDict  valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]]] dateByAddingTimeInterval:21600.0*u] ;//6 hr
            localNotification2.repeatInterval=NSDayCalendarUnit;

            localNotification2.alertBody = [NSString stringWithFormat:@"Friendly reminder to take %@ %@ at %@.",[MedicationDict objectForKey:@"DrugName"],[MedicationDict objectForKey:@"Frequency"],[MedicationDict objectForKey:@"Ending"]];

            localNotification2.alertAction = @"Notification";
            localNotification2.soundName=UILocalNotificationDefaultSoundName;
            localNotification2.applicationIconBadgeNumber = 4;


            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];

            NSLog(@"all notifications %@",[[UIApplication sharedApplication]scheduledLocalNotifications]);

        }


      //  localNotification2.repeatInterval=NSDayCalendarUnit;
   }  
 //   localNotification2.repeatInterval=NSDayCalendarUnit;

    NSLog(@"date is %@ %@",[MedicationDict valueForKey:@"Starting"],[MedicationDict valueForKey:@"Ending"]);

    localNotification2.timeZone = [NSTimeZone localTimeZone];


     localNotification2.alertBody = [NSString stringWithFormat:@"Friendly reminder to take %@ %@ at %@.",[MedicationDict objectForKey:@"DrugName"],[MedicationDict objectForKey:@"Frequency"],[MedicationDict objectForKey:@"Ending"]];

    localNotification2.alertAction = @"Notification";
    localNotification2.soundName=UILocalNotificationDefaultSoundName;
    //localNotification2.applicationIconBadgeNumber = 1;

  //  infoDict = [NSDictionary dictionaryWithObject:id1 forKey:@"did"];

  //  localNotification2.userInfo = infoDict;

  //  [[UIApplication sharedApplication] scheduleLocalNotification:localNotification2];

 //   NSLog(@"all notifications %@",[[UIApplication sharedApplication]scheduledLocalNotifications]);

   // [[UIApplication sharedApplication] cancelAllLocalNotifications];//dk
 }
Share:
52,173

Related videos on Youtube

Parth Bhatt
Author by

Parth Bhatt

I am iPhone and iPad developer. https://github.com/akashraje/BidirectionalCollectionViewLayout ^[-_,A-Za-z0-9]$ NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:@"(#[a-zA-Z0-9_-]+)" options:NSRegularExpressionCaseInsensitive error:nil]; NSString *stringData = @"This is Parth known as #parth and this is an awesome place. I am fan of #scganguly."; int count = [reg numberOfMatchesInString:stringData options:0 range:NSMakeRange(0, [stringData length])]; NSLog(@"%d",count); if(count&gt;0) { NSArray *array = [reg matchesInString:stringData options:0 range:NSMakeRange(0, [stringData length])]; NSLog(@"%@",array); NSMutableArray *stringArray = [[NSMutableArray alloc] init]; for (NSTextCheckingResult *result in array) { NSString *stringFinal = [stringData substringWithRange:result.range]; if(stringFinal != nil) { [stringArray addObject:stringFinal]; } } NSLog(@"stringArray: %@",stringArray); } For @user: @"(@[a-zA-Z0-9_]+)" NSLog(@"Request String: %@", requestString); NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; // NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"url" ofType:@"plist" ]; // NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc]; // NSString *urlLoc = [fileContents objectForKey:@"baseURL"]; NSString *urlLoc = @"http://portal.abc.com/candidate/post-info"; NSLog(@"URL is %@",urlLoc); NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]]; NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]]; [request setHTTPMethod: @"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody: requestData]; http://blog.stackoverflow.com/archive/ https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/CocoaTouch64BitGuide/Introduction/Introduction.html http://nscookbook.com/2013/03/ios-programming-recipe-19-using-core-motion-to-access-gyro-and-accelerometer/ http://code4app.net/category/coremotion http://www.devx.com/wireless/Article/44799 upload audio file to php ios Android post request on IOS https://developers.facebook.com/docs/ios/share https://github.com/oliverbarreto/FastFavs/blob/master/TODO2.h

Updated on July 09, 2022

Comments

  • Parth Bhatt
    Parth Bhatt almost 2 years

    I am making an iPhone app, which has a requirement of Local Notifications.

    In local notifications there is repeatInterval property where we can put the unit repeat intervals for mintute, hour, day,week,year, etc.

    I want that repeat interval should be 4 hours.

    So every 4 hours the local notification comes.

    I dont want the user to set seperate notifications for each.

    I want the user to be able to set repeatInterval as 4 hours.

    How do I do that?

  • Robin Summerhill
    Robin Summerhill over 12 years
    However, see this answer. It gives a way to achieve this if you can live with the 64 notification limit.
  • Bandish Dave
    Bandish Dave over 8 years
    :: very nice...can you please help me which method is called when my app is in background or in killed mode? because i want to display dynamic text on notification banner based on "uid". Replay me ASAP
  • Doro
    Doro over 8 years
    @BandishDave, - (void)applicationWillResignActive:(UIApplication *)application - This method is called to let your app know that it is about to move from the active to inactive state. This can occur for certain types of temporary interruptions. Also, see - (void)applicationWillTerminate:(UIApplication *)application - This method lets your app know that it is about to be terminated and purged from memory entirely.
  • Ace Green
    Ace Green over 8 years
    any way we can use repeatInterval for also 3, 5, 7 day interval?
  • Ace Green
    Ace Green over 8 years
    How does Apples reminders app schedule repeat intervals of specific day of week or every x days etc. I doubt they are scheduling each and every one or? they also would run out of 64 allocation limit for their app
  • Mehul
    Mehul about 8 years
    You could try to set repeat interval for each day and then removes the notifications for the days required.
  • Abhishek Thapliyal
    Abhishek Thapliyal over 7 years
    i'm not statisfy with this answer as whatsapp show notification every 3-4 secs when app is in background and and VOIP call comes
  • RtmY
    RtmY about 5 years
    Can you please add a description?