我有一个对象,它将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];
}
当我记录itemDate时间时,这就是我想要的。在方法结束时,本地通知会立即触发。我不确定为什么因为我的日期是正确的时间,我想我只是将fireDate设置为那个日期?感谢。
答案 0 :(得分: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];
答案 1 :(得分:4)
要立即发出通知,您应该使用
presentLocalNotificationNow
而不是
scheduleLocalNotification