Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

ios4 - iPhone: How to set repeat daily/hourly local notification?

I want to test add local notification. I want it repeat daily/hourly. How can I do that?

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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to set the Notifications at a particular time on daily ... .then you need to set the notification repeatInterval property.iOS handles of it;s own about the notification.Just add this single line ...which you missed out. Otherwise you code is fine & will work.

notif.repeatInterval = NSDayCalendarUnit;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...