2010-08-06 94 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];