2015-11-14 66 views
2

我尝试每周一重复本地通知。我发现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]; 
+1

我在上面的代码中看到注释掉的'fireData'行。为什么不尝试设置一个本地通知,每隔30分钟触发一次,看看它是否可行? –

+0

其实是一个好主意。我会尝试。谢谢 – hantoren

+0

我发现,localNotification.repeatInterval = NSCalendarUnitMinute;将每分钟重复一次该代码。但是我想每个星期一都有一个通知,所以我必须改变代码中的内容吗?我不确定是否必须使用localNotification.repeatInterval = NSCalendarUnitWeekOfYear/NSCalendarUnitWeekday或kCFCalendarUnitWeekOfYear ... – hantoren

回答

3

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

我会推荐唯一的变化使得将是:

localNotification.repeatInterval = NSCalendarUnitWeekOfYear; 

我发现in this very related question

此外,编译器会抱怨,如果你使用像线:

[nowComponents setMinute:08]; 

(因为它解释,作为一个八进制数的而不是整数)。不要使用前导零。做类似:

[nowComponents setMinute:8]; 

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