Crystal
Crystal

Reputation: 29518

UILocalNotification fires immediately instead of at scheduled time

I have an object that stores times in an NSArray as a NSString. I chose NSString since that's what I end up displaying a lot instead of the NSDate. I'm trying to setup a UILocalNotification for it. What I've done is:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
dateFormatter.dateFormat = @"h:mm a";

for (NSString *s in _times) {
    NSDate *date = [dateFormatter dateFromString:s];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit)
                                                   fromDate:date];
    NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:[dateComponents day]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]];
    [dateComps setMinute:[timeComponents minute]];

    NSDate *itemDate = [calendar dateFromComponents:dateComps];

    NSLog(@"%@", [dateFormatter stringFromDate:itemDate]);
    UILocalNotification *note = [[UILocalNotification alloc] init];
    note.alertAction = thePill.name;
    note.alertBody = thePill.note;
    note.fireDate = itemDate;
    note.timeZone = [[NSCalendar currentCalendar] timeZone];

    if (note.fireDate == nil) {
        NSLog(@"nil firedate");
    }

//        note.repeatInterval = NSDayCalendarUnit;

    NSData *data = [self archivePill:thePill];
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:data forKey:PILL_NOTIFICATION];
    note.userInfo = infoDict;

    [[UIApplication sharedApplication] scheduleLocalNotification:note];
}

When I NSLog the itemDate time, it is what I want. At the end of the method, the local notification fires immediately instead at that time. I'm not sure why since my date is the right time, and I thought I just set the fireDate to that date? Thanks.

Upvotes: 2

Views: 5651

Answers (2)

watxaut
watxaut

Reputation: 49

To fire a notification immediately you should use

presentLocalNotificationNow

Instead of

scheduleLocalNotification

Upvotes: 4

A R
A R

Reputation: 461

// Fire notification immediately after 1 sec 
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
localNotification.alertBody = @"Your alert message";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

Upvotes: 4

Related Questions