我正在开发一项功能,允许用户安排接收通知的日期和时间 .
到目前为止,时间和消息功能都很有效 . 我被困在哪里是重复间隔 .
这是我尝试过的:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *formatedDate = [dateFormatter stringFromDate:self.datePicker.date];
self.currentTimeLabel.text = formatedDate;
NSDate *date = [dateFormatter dateFromString:self.currentTimeLabel.text];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
[components setHour:hour];
[components setMinute:minute];
if ([self.currentRepeatLabel.text containsString:@"Sun"]) {
[components setWeekday:0];
self.notification = [[UILocalNotification alloc] init];
self.notification.fireDate = [calendar dateFromComponents:components];
self.notification.repeatInterval = NSCalendarUnitDay;
[self.notification setAlertBody:[NSString stringWithFormat:@"A friendly reminder: %@", self.titleStringToDisplay]];
if (self.soundSwitch.isOn == YES) {
self.notification.soundName = @"soundeffect.wav";
}
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:self.titleStringToDisplay forKey:@"title"];
self.notification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:self.notification];
}
if ([self.currentRepeatLabel.text containsString:@"Mon"]) {
[components setWeekday:1];
self.notification = [[UILocalNotification alloc] init];
self.notification.fireDate = [calendar dateFromComponents:components];
self.notification.repeatInterval = NSCalendarUnitDay;
[self.notification setAlertBody:[NSString stringWithFormat:@"A friendly reminder: %@", self.titleStringToDisplay]];
if (self.soundSwitch.isOn == YES) {
self.notification.soundName = @"soundeffect.wav";
}
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:self.titleStringToDisplay forKey:@"title"];
self.notification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:self.notification];
}
// I'm doing this for each day.
_996767_每天都在重复我的通知,无论我选择了什么日子 . 我已经尝试了 NSCalendarUnitWeekOfYear
但是我的通知在使用时从未触发过 .
目标是让用户设置他们的 Headers ,时间和重复天数(很像本机警报应用程序) .
如何为此设置重复间隔?
更新和新问题:
我现在正在使用 NSCalendarUnitWeekOfYear
.
这是我的问题......现在不再触发通知,并且repeatInterval始终设置为星期一,而不是它在代码中逐步执行的星期几 .
2 回答
有几种方法可以做到这一点 . 您可以使用NScalender查找工作日,然后计算要通知的日期 .
你的代码有很多问题 .
你的日期明显来自
UIDatePicker
. 你应该使用这个日期 . 来回转换是无稽之谈 .此外,摆脱所有重复的代码 . 它使得理解(和修复)代码变得更加困难 . 它隐藏了逻辑 .
但真正的问题是你只需将日期组件设置为日期 . 它不是 . 您开始将一些日期投入组件,然后设置工作日 . 这不会给出另一个有效的日期 - 为什么要这样?怎么可能?它应该调整什么?那天?这个月?那一年?走进未来还是走向过去?转换为约会时,工作日似乎被忽略了 .
您需要计算一个正确的日期(this answer描述计算下一个星期一) .