问题
I have a method that makes the store of a UILocalNotification:
- (void)save:(NSString *)program at:(NSDate*)date {
NSLog(@"date to save: %@", date);
// NSLog(@"timezone: %@",[date descriptionWithLocale:[NSLocale systemLocale]]);
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
NSLog(@"date to fire: %@", date);
localNotification.fireDate = date;
NSString *s=[program stringByAppendingString:@" is now on "];
NSString *title=[s stringByAppendingString:channel];
localNotification.alertBody = title;
localNotification.alertAction = @"Show...";
//localNotification.timeZone = [NSTimeZone localTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSLog(@"notification to save %@",localNotification);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// Request to reload table view data
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:self];
// Dismiss the view controller
[self dismissViewControllerAnimated:YES completion:nil];
}
And I have as output:
date to save: 2013-08-29 17:00:00 +0000
date to fire: 2013-08-29 17:00:00 +0000
notification to save <UIConcreteLocalNotification: 0xc0c4240>{fire date = Thursday, August 29, 2013, 6:00:00 PM Central European Standard Time, time zone = (null), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Thursday, August 29, 2013, 6:00:00 PM Central European Standard Time, user info = (null)}
Despite uncommenting the timezone setting, the UILocalNotification is always incrementing by one hour, why, and how ? Thank you for helping.
回答1:
The date you pass in in GMT, which in you case is does not match your local time zone.
So when you set the date to 17:00 your time corrects it to you timezone (CET) which is GMT+1. Thus an hour gets added to you date.
A solution is to set the UILocalNotification timezone to GMT:
localNotification.timeZone = [NSTimeZone timeZoneWithName@"GMT"];
From the Apple documentation:
The date specified in fireDate is interpreted according to the value of this property. If you specify nil (the default), the fire date is interpreted as an absolute GMT time, which is suitable for cases such as countdown timers. If you assign a valid NSTimeZone object to this property, the fire date is interpreted as a wall-clock time that is automatically adjusted when there are changes in time zones; an example suitable for this case is an an alarm clock.
来源:https://stackoverflow.com/questions/18511533/uilocalnotification-always-setting-the-date-to-local-timezone