我有一个对象,它将时间作为 NSString 存储在 NSArray 中。我选择了 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 设置为该日期?谢谢。
最佳答案
// 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];
关于objective-c - UILocalNotification 立即触发,而不是在预定时间触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10060578/