2015-11-14 141 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,否則它們根本不會出現。