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
316 views
in Technique[技术] by (71.8m points)

ios - Fire a notification at a specific day and time every week

I want to trigger a UILocalNotification every Sunday at 8PM, however, I'm having a fire date every day at 8PM.

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit |   NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];
    [componentsForFireDate setWeekday: 1] ; //for fixing Sunday
    [componentsForFireDate setHour: 20] ; //for fixing 8PM hour
    [componentsForFireDate setMinute:0] ;
    [componentsForFireDate setSecond:0] ;

    NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForFireDate];
    UILocalNotification *notification = [[UILocalNotification alloc]  init] ;
    notification.fireDate = fireDateOfNotification ;
    notification.timeZone = [NSTimeZone localTimeZone] ;
    notification.alertBody = [NSString stringWithFormat: @"New updates!"] ;
    notification.userInfo= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"New updates added for that week!"] forKey:@"new"];
    notification.repeatInterval= NSDayCalendarUnit ;
    notification.soundName=UILocalNotificationDefaultSoundName;

    NSLog(@"notification: %@",notification);//it indicates that the notif will be triggered today at 8PM and not Sunday.

    [[UIApplication sharedApplication] scheduleLocalNotification:notification] ;

Thank you.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You missed the NSWeekCalendarUnit in the NSDateComponents init function. Add the NSWeekCalendarUnit to it and set the repeatInterval to NSWeekCalendarUnit, then output is

next fire date = Sunday, November 24, 2013 at 8:00:00 PM  

The code is here:

  NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *componentsForFireDate = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit) fromDate: now];
[componentsForFireDate setWeekday: 1] ; //for fixing Sunday
[componentsForFireDate setHour: 20] ; //for fixing 8PM hour
[componentsForFireDate setMinute:0] ;
[componentsForFireDate setSecond:0] ;

  //...
  notification.repeatInterval = NSWeekCalendarUnit;
  //...

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

...