Я хочу установить UILocalNotification, чтобы уйти в определенное время. Приложение занимается заказом ресторанов. Если заказ сделан и назначение больше чем через 2 часа, то я хочу показать уведомление за 2 часа до него. Если это больше, чем 1 час, я должен был показать это за 1 час до начала, иначе я хочу показать это за 15 минут до руки. Мне кажется, что мое время UILocalNotification не соответствует + 1 hour
. Ниже используется код:Неправильная дата огня UILocalNotification - дата огня на один час вперед
[self setLocalNotificationWithAlertBody:@"Alert Body goes here" AndWithBookingDateString:@"2015-09-07 19:45:00"];//the booking time
-(void)setLocalNotificationWithAlertBody:(NSString *)body AndWithBookingDateString:(NSString *)dateString{
NSLog(@"Date String %@",dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"Date from String %@",[dateFormatter dateFromString:dateString]);
[self setLocalNotificationWithAlertBody:body AndWithBookingDate:dateFromString];
}
-(void)setLocalNotificationWithAlertBody: (NSString *) body AndWithBookingDate: (NSDate *)date{
NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit
fromDate:currentDate
toDate:date
options:0];
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
NSInteger hour = [components hour];
if (components.hour>=2) {//remind the user 2 hours before hand if booking is made greater than 2 hours
NSTimeInterval secondsPerHour = (60 * 60)*2;//two hours before appointment
NSDate *givenDate = date; // what you have already
NSDate *earlierDate = [givenDate dateByAddingTimeInterval:-secondsPerHour];
NSLog(@"\n\n Greater than 2 hours %@ \n\n",earlierDate);
localNotification.fireDate=earlierDate;
localNotification.alertBody = [NSString stringWithFormat:@"%@ %@",body,[self getDeviceShortDateFromString:[NSString stringWithFormat:@"%@",date] WithFormat:@"yyyy-MM-dd HH:mm:ss ZZZZZ"]];
}
else if (components.hour>1) {
NSTimeInterval secondsPerHour = 60 * 60;
NSDate *givenDate = date; // what you have already
NSDate *earlierDate = [givenDate dateByAddingTimeInterval:-secondsPerHour];
NSLog(@"\n\n Greater than an hour %@ \n\n",earlierDate);
localNotification.fireDate=earlierDate;
localNotification.alertBody = [NSString stringWithFormat:@"%@ %@",body,[self getDeviceShortDateFromString:[NSString stringWithFormat:@"%@",date] WithFormat:@"yyyy-MM-dd HH:mm:ss ZZZZZ"]];
}
else{
NSTimeInterval secondsPer15mins = 15 * 60;
NSDate *givenDate = date; // what you have already
NSDate *earlierDate = [givenDate dateByAddingTimeInterval:-secondsPer15mins];
NSLog(@"\n\n Less than one hour %@ \n",earlierDate);
localNotification.fireDate=earlierDate;
localNotification.alertBody = [NSString stringWithFormat:@"%@ %@",body,[self getDeviceShortDateFromString:[NSString stringWithFormat:@"%@",date] WithFormat:@"yyyy-MM-dd HH:mm:ss ZZZZZ"]];
}
localNotification.userInfo = @{@"key" : body};
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
NSLog(@"Fire date %@",localNotification.fireDate);
NSLog(@"Notification--->: %@", localNotification);
}
-(NSString *)getDeviceShortDateFromString: (NSString *) date WithFormat: (NSString *)format{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:format];
NSDate * tempDate =[dateFormatter dateFromString: date];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:@"MMM yyyy"];
if (tempDate == nil) {
return @" ";
}
return [dateFormatter2 stringFromDate:tempDate];
}
дата пожара регистрации как:
Fire date 2015-09-07 17:45:00 +0000
Но местное уведомление неверно:
Notification--->: <UIConcreteLocalNotification: 0x174178300>{fire date = Monday 7 September 2015 18:45:00 Irish Summer Time, time zone = (null), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Monday 7 September 2015 18:45:00 Irish Summer Time, user info = {
key = "Alert Body Goes here";
}}
назначение было заказанные больше чем 2 часа, так уведомление должно быть отключено в 5:45, но оно не уходит до 6:45. Любая помощь приветствуется.
«Помоги мне StackOverflow, ты моя единственная надежда» :)
Если это для пользователей собственного часового пояса почему он не установлен в часовом поясе системы? Если я пользователь, использующий это приложение, и я планирую бронирование через 2 часа, это должно быть через два часа из моего соответствующего часового пояса правильно? Если вы не пытаетесь съесть кого-то с часовыми поясами GMT – soulshined
@soulshined хорошо заметили, спасибо за это. – DevC