我想测试添加本地通知。我希望它每天/每小时重复一次。我怎么能这样做?
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];
答案 0 :(得分:12)
如果您想在每天的特定时间设置通知...。然后您需要设置通知 repeatInterval property.iOS处理它; s拥有通知。只需添加这条单线...你错过了。否则你的代码很好&会工作的。
notif.repeatInterval = NSDayCalendarUnit;
答案 1 :(得分:2)
如果您使用dateByAddingComponents:toDate:options:。
,您的代码会更简单(dateByAddingTimeInterval:无法正确处理日历,例如时区更改。)
如果你想重复它,我认为你必须添加几个,或者在你的应用下次启动时重新添加它们。否则,每秒重复一次的通知会令人非常恼火。
答案 2 :(得分:2)
答案 3 :(得分: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];