2

我有一个将 NSArray 中的时间存储为 NSString 的对象。我选择了 NSString,因为那是我最终显示的而不是 NSDate。我正在尝试为它设置一个 UILocalNotification 。我所做的是:

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];
}

当我 NSLog itemDate 时间时,这就是我想要的。在方法结束时,本地通知会立即触发。我不确定为什么,因为我的日期是正确的时间,我以为我只是将 fireDate 设置为那个日期?谢谢。

4

2 回答 2

4
// 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];
于 2013-08-07T07:03:45.113 回答
4

要立即触发通知,您应该使用

presentLocalNotificationNow

代替

scheduleLocalNotification
于 2015-09-24T07:52:57.270 回答