iOS7之前localNotification.repeatInterval = NSWeekCalendarUnit可以设置按周提醒。iOS7之后NSWeekCalendarUnit被去掉
取而代之的是NSCalendarUnitWeekOfMonth和NSCalendarUnitWeekOfYear
但是使用NSCalendarUnitWeekOfMonth时next fire date = null 到时候并不提醒
NSCalendarUnitWeekOfYear正常
NSCalendarUnit包含的值有:
NSCalendarUnitEra --
NSCalendarUnitYear -- 年单位。相当于经历了多少年,未来多少年。
NSCalendarUnitMonth -- 月单位。范围为1-12
NSCalendarUnitDay -- 按天重复。范围为1-31
NSCalendarUnitHour -- 每小时提醒。范围为0-24
NSCalendarUnitMinute -- 每分钟提醒。范围为0-60
NSCalendarUnitSecond -- 秒单位。范围为0-60
NSCalendarUnitWeekday -- 星期单位,每周的7天。范围为1-7
NSCalendarUnitWeekdayOrdinal --
NSCalendarUnitQuarter -- 几刻钟,也就是15分钟。范围为1-4
NSCalendarUnitWeekOfMonth -- 一个月每周提醒。最多为6个周
NSCalendarUnitWeekOfYear -- 一年每周提醒。范围为1-53 最多为53个周
NSCalendarUnitYearForWeekOfYear --
NSCalendarUnitTimeZone --
1.计算出要提醒的日期
// weekDay代表设置的哪天要提醒
- (NSDate *)setDateForAlarmWithWeekday:(NSInteger)weekDay settingTime:(NSString*)timeString
{
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone defaultTimeZone]];
unsigned currentFlag = NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear|NSCalendarUnitWeekday;
NSDateComponents *comp = [calendar components:currentFlag fromDate:[NSDate date]];
NSInteger hour = [[[timeString componentsSeparatedByString:@":"] objectAtIndex:0] intValue];
NSInteger min = [[[timeString componentsSeparatedByString:@":"] objectAtIndex:1] intValue];
comp.hour = hour;
comp.minute = min;
comp.second = 0;
NSInteger diff = (weekDay - comp.weekday);
NSInteger multiplier;
if (weekDay == 0) {
multiplier = 0;
}else {
//今天注册今天提醒
multiplier = diff > 0 ? diff:(diff == 0 ? diff : diff+7);
// multiplier = diff > 0 ? diff:diff+7;
}
return [[calendar dateFromComponents:comp] dateByAddingTimeInterval:multiplier*3600*24];
}
2.注册多个通知,礼拜一注册个,礼拜三注册一个
- (void)notificationWithDate:(NSDate *)date time:(NSString *)time{
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = date;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatCalendar = [NSCalendar currentCalendar];
NSString *alertBody = F(@"%@了,该睡觉了!", time);
localNotification.alertBody = alertBody;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.repeatInterval = NSCalendarUnitWeekOfYear;
NSDictionary *infoDict = @{@"notif":@"GoodnightCall"};
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}