我想每周晚上10点(不论国家/地区)发出通知。我需要使用timeZone吗?目前我使用下面的代码来解雇每周的通知,但是如何在晚上10点准确发布通知。
NSDate *date = [NSDate date];
NSDate* myNewDate = [date dateByAddingTimeInterval:7*24*60*60];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = myNewDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSWeekCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];
答案 0 :(得分:4)
我认为将fireDate设置为您想要收到通知的那天的22:00(而不是“从现在开始的一周”)可以满足您的需求。您可能希望使用NSCalendar
来执行此操作。
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
NSDate *currentDate = [NSDate date];
NSDate *fireDate = nil;
[dateComponents setDay:3]; // ...or whatever day.
[dateComponents setHour:22];
[dateComponents setMinute:0];
fireDate = [gregorian dateByAddingComponents:dateComponents
toDate:currentDate
options:0];
[localNotification setFireDate:fireDate];
[dateComponents release];
答案 1 :(得分:0)
我做了这些修改并且有效......
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
NSDate *currentDate = [NSDate date];
NSDate *fireDate = nil;
//Getting current Hour
NSDateComponents *components = [[NSCalendar currentCalendar] components:(kCFCalendarUnitHour | kCFCalendarUnitMinute) fromDate:currentDate];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
[dateComponents setDay:7];//After 1 week
[dateComponents setHour:22-hour-1]; //Calculating Remaining time for 10PM && "-1" because i am adding 60 min
[dateComponents setMinute:60-minute];
//Adding remaining time to current Time
fireDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents
toDate:currentDate
options:0];
[localNotification setFireDate:fireDate];