【问题标题】:Fire UILocalNotification Weekly每周触发 UILocalNotification
【发布时间】:2012-10-04 23:37:15
【问题描述】:

我似乎无法弄清楚为什么这个通知没有安排在星期六...我已经尝试了 NSGregorianCalendarautoupdatingCurrentCalendar。我正在设置[dateComps setWeekday:7];,但它会在周日不断返回。

//NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *timeComponent = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:reminderTime];
 // Set up the fire time
 NSDateComponents *dateComps = [[NSDateComponents alloc] init];
 [dateComps setYear: 2012];;
 [dateComps setHour: timeComponent.hour];
 [dateComps setMinute: timeComponent.minute];
 [dateComps setSecond:0];
 // Set day of the week
 [dateComps setWeekday:7];
 NSDate *itemDate = [calendar dateFromComponents:dateComps];

 UILocalNotification *notification = [[UILocalNotification alloc] init];
 if (notification == nil)
     return;
 notification.fireDate = itemDate;
 notification.repeatInterval = NSWeekCalendarUnit;

【问题讨论】:

    标签: iphone objective-c ios uilocalnotification nscalendar


    【解决方案1】:

    dateComps 在您计算时不包含日期或月份,因此 setWeekday 将被忽略,itemDate 是 2012 年 1 月的第一个日期(这是星期日)。

    要计算下一个星期六,您可以按照“日期和时间编程指南”的Adding Components to a Date 中的说明进行操作:

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    // Weekday of "reminderTime":
    NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:reminderTime];
    
    // Number of weekdays until next Saturday:
    NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
    [componentsToAdd setDay: 7 - [weekdayComponents weekday]];
    
    NSDate *itemDate = [calendar dateByAddingComponents:componentsToAdd toDate:reminderTime options:0];
    

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多