Question

In iOS, I wanted to schedule a notification to inform the user after 48 hours since he closes the app. In addition to the 48 hours, it has to be shown at 7p.m. of the day.

For example: Current time is 5 p.m, the user closes the app. Then the notification should popup after 2 days at 5 p.m as well, but I want it to delay until 7 p.m. How should I write my codes in order to achieve this with the mentioned criteria?

Was it helpful?

Solution

In - (void)applicationWillResignActive:(UIApplication *)application method,

  1. calculate the actual time to be shown, i.e. 48 hours + hours to 7pm of that day.
  2. cancel any current scheduled notification
  3. create a UILocalNotification and set the parameters needed (time to fire and alert text).

Edit based on comment:

If I understand you this should be what you want. It calculates a time that is 48 hours later, and manually set the fire time to 7pm. If the calculated time is greater than 7pm, it will be fired on the next day.


NSDate *currentDate = [NSDate date];
NSDate *futureTime = [currentDate dateByAddingTimeInterval:60*60*48];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
[calendar setTimeZone:timeZone];

NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit fromDate:futureTime];
if ([components hour] >= 19) { // make it the next day 
    [components setDay:[components day] + 1 ];
}
[components setHour:19];
[components setMinute:00];
NSDate *alertTime = [calendar dateFromComponents:components];

OTHER TIPS

   NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];
    [DateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date =[NSDate dateWithTimeInterval:60*60*48 sinceDate:[NSDate date]];
    NSString *dateString=[DateFormatter stringFromDate:date];

    NSInteger timeLater=[dateString substringWithRange:NSMakeRange(11, 2)].integerValue;
    if(timeLater<19)
        date =[date dateByAddingTimeInterval:(19-timeLater)*60*60];
    dateString=[DateFormatter stringFromDate:date];
    NSLog(@"%@",dateString);


notification.fireDate =date.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top