2010-08-06 157 views
2

我想測試添加本地通知。我希望每天/每小時重複一次。我怎樣才能做到這一點?iPhone:如何設置重複每日/每小時本地通知?

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar]; 

// Get the current date 
    NSDate *now = [NSDate date]; 

// Break the date up into components 
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit |  NSMonthCalendarUnit | NSDayCalendarUnit) 
      fromDate:now]; 

NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) 
      fromDate:now]; 


// Set up the fire time 
NSDateComponents *dateComps = [[NSDateComponents alloc] init]; 

[dateComps setDay:[dateComponents day]]; 
[dateComps setMonth:[dateComponents month]]; 
[dateComps setYear:[dateComponents year]]; 

[dateComps setHour:[timeComponents hour]]; 
[dateComps setMinute:[timeComponents minute]]; 
[dateComps setSecond:[timeComponents second]+10]; 

// Notification will fire in one minute 

NSDate *itemDate = [calendar dateFromComponents:dateComps]; 
[dateComps release]; 

UILocalNotification *localNotif = [[UILocalNotification alloc] init]; 
if (localNotif == nil) 
    return; 

localNotif.fireDate = itemDate; 
localNotif.timeZone = [NSTimeZone defaultTimeZone]; 

// Notification details 
localNotif.alertBody = @"Hello World"; 

// Set the action button 
localNotif.alertAction = @"View"; 
localNotif.soundName = UILocalNotificationDefaultSoundName; 

applicationIconBadgeNumber++; 

localNotif.applicationIconBadgeNumber = applicationIconBadgeNumber; 

// Schedule the notification 
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
[localNotif release]; 
+2

你可以嘗試格式正確的代碼。 – 2010-08-06 19:13:24

回答

2

如果你使用了dateByAddingComponents:toDate:options :.你的代碼會簡單得多。

(dateByAddingTimeInterval:不處理日曆正確,如時區變化)

如果你想讓它重複,我認爲你必須添加幾個,或重新添加他們當你的應用未來推出。否則,每秒重複一次的通知會令人難以置信的煩人。

12

如果你想在每日特定時間設定通知...。然後你需要設置通知按repeatInterval property.iOS它的手柄;自己關於通知。只需添加這條單行......你錯過了。否則,你的代碼是好的&將工作。

notif.repeatInterval = NSDayCalendarUnit; 
+1

我們可以使用NSDayCalendarUnit的隨機時間?我想每天做一次隨機本地通知,隨機一次Basis ... PLease Help – 2014-03-29 07:10:51

+0

@shaqirsaiyed:你可能不得不手動創建每個隨機日的開火時間,這不是一個正常的「重複間隔」。 – mix3d 2015-06-23 15:53:30

1
UILocalNotification *localNotif = [[UILocalNotification alloc] init]; 
if (localNotif == nil) return; 

NSDate *fireTime = [[NSDate date] dateByAddingTimeInterval:900]; // 15 minutes 

localNotif.fireDate = fireTime; 
localNotif.alertBody = @"15 min reached"; 
localNotif.repeatInterval=kCFCalendarUnitMinute; 
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];