每周一重复本地通知

Repeat local notification every Monday

我尝试每周一重复本地通知。我找到 localNotification.repeatInterval = kCFCalendarUnitWeekOfYear; 但我不确定它是否有效。以后如何显示所有本地通知时间?

[[UIApplication sharedApplication] cancelAllLocalNotifications];

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setLocale:[NSLocale currentLocale]];

NSDateComponents *nowComponents = [gregorian components:NSCalendarUnitYear | NSCalendarUnitWeekOfYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:today];

[nowComponents setHour:18];
[nowComponents setMinute:05];
[nowComponents setSecond:00];
[nowComponents setWeekday:2];

NSDate * notificationDate = [gregorian dateFromComponents:nowComponents];

UILocalNotification* localNotification = [[UILocalNotification alloc] init];
//localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
localNotification.fireDate = notificationDate;
localNotification.repeatInterval = kCFCalendarUnitWeekOfYear;
localNotification.soundName = @"localNotification_Sound.mp3";
localNotification.alertBody = @"Message?";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

我在自己的模拟器中测试了你的代码,它似乎工作得很好。

我建议做的唯一改变是:

localNotification.repeatInterval = NSCalendarUnitWeekOfYear;

我找到了

此外,如果您使用以下行,编译器会报错:

[nowComponents setMinute:08];

(因为它将其解释为八进制数而不是整数)。不要使用前导零。做类似的事情:

[nowComponents setMinute:8];

别忘了ask your user to enable notifications,否则根本不会出现。