所以,我知道星期一是 = 2
,现在当我说星期二是 = 3
时,它不会触发。
要么是我没有正确设置日期,要么是 calendar components
的 NSWeekCalendarUnit
和 repeatinterval
是错误的!
现在我的奇迹是:
day components
是否等于 1
到 7
从星期日开始?
另外,它应该是一个 NSDayCalendarUnit
还是我做对了?
看看我的代码,看看你能不能修复它。谢谢
-(void) tuesday { // every tuesday
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
NSDateComponents *components = [calendar components:NSWeekCalendarUnit fromDate:[NSDate date]];
components.day = 1;
components.hour = 18;
components.minute = 55;
components.second = 45;
NSDate *fireDate = [calendar dateFromComponents:components];
NSLog(@"Tuesday %@", fireDate);
UILocalNotification *notif = [[UILocalNotification alloc] init] ;
if (notif == nil)
return;
notif.fireDate = fireDate;
notif.repeatInterval= NSWeekCalendarUnit ;
notif.soundName = @"ring.wav";
notif.alertBody = [NSString stringWithFormat: @"Hello World"] ;
[[UIApplication sharedApplication] scheduleLocalNotification:notif] ;
}
更新:
这是我得到的日志:
2014-01-19 18:55:09.258 daily notification test[14609:c07] Tuesday 0001-01-01 18:55:45 +0000
最佳答案
您的问题似乎是,您将组件添加到 NSDate,但没有设置相关的日期参数。要触发您的通知,您需要定义下周二的 NSDate。
希望这个例子对你有所帮助:
//first you have to check what's the current weekday
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//Set timezone if needed
gregorian.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int currentWeekday = [comps weekday] ;
NSLog(@"currentWeekDay:%d", currentWeekday);
//After you know which weekday it is, you can check how many days to add till tuesday
int daysToAdd;
switch (currentWeekday) {
//Sunday to Tuesday
case 1:
daysToAdd = 2;
break;
//Monday to Tuesday
case 2:
daysToAdd = 1;
break;
//Tuesday to Tuesday
case 3:
daysToAdd = 0;
break;
//Wednesday to Tuesday
case 4:
daysToAdd = 6;
break;
//Thursday to Tuesday
case 5:
daysToAdd = 5;
break;
//Thursday to Tuesday
case 6:
daysToAdd = 4;
break;
case 7:
daysToAdd = 3;
break;
default:
daysToAdd = 0;
break;
}
NSDate *firetime = [[NSDate alloc] init];
NSDateComponents *timeCorrection = [[NSDateComponents alloc] init];
[timeCorrection setHour:18];
[timeCorrection setMinute:55];
[timeCorrection setSecond:45];
firetime = [[NSCalendar currentCalendar] dateByAddingComponents:timeCorrection toDate:firetime options:0];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:daysToAdd];
firetime = [gregorian dateByAddingComponents:offsetComponents toDate:firetime options:0];
//this should be your fire date
NSLog(@"Next tuesday:%@",firetime);
希望这就是您正在寻找的,或者给您正确的提示。尚未测试。
问候, 扎拉卡斯
关于ios - 每个星期二的本地通知重复间隔不起作用..我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21217872/