自定义本地推送通知(UILocalNotification) 星期和时间

阅读更多

 

//创建本地通知

UILocalNotification *localNote = [[UILocalNotificationalloc] init];

//自定义(星期和时间)

NSDate * newDate = [selfgetNextWeekDay:2hour:20minute:25];

    self.localNote.fireDate = newDate;

//设置重复周期为:(若每天重复使用属性NSCalendarUnitDayNSCalendarUnitWeekDay)

    self.localNote.repeatInterval = kCFCalendarUnitWeek;

    self.localNote.timeZone = [NSTimeZonedefaultTimeZone];

    self.localNote.alertLaunchImage = @"default-banner.png";

    self.localNote.hasAction = YES;

    self.localNote.soundName = UILocalNotificationDefaultSoundName;

    self.localNote.alertAction = @"通知";

 

    self.localNote.alertBody = @"新的通知~~!";

//    移除旧的通知,防止重复添加

    [[UIApplicationsharedApplication] cancelAllLocalNotifications];

 

    [[UIApplicationsharedApplication] scheduleLocalNotification:self.localNote];

 

/**

 *  获取下一个新的星期日期

 *

 *  @param newWeekDay 星期数值从周日算起,星期日1/星期一2/星期二3...星期六7

 *  @param hour       设定的小时值

 *  @param minute     设定的分钟值

 *

 *  @return返回新的日期(NSDate对象)

 */

 

-(NSDate *)getNextWeekDay:(int)newWeekDay hour:(int)hour minute:(int)minute{

    NSDateComponents * components = [[NSCalendarcurrentCalendar] components:NSCalendarUnitWeekday|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecondfromDate:[NSDatedate]];

    

    HTLog(@"设置的weekday = %d", newWeekDay);

    

    NSDateComponents *comps = [[NSDateComponentsalloc] init] ;

    

    NSInteger unitFlags = NSCalendarUnitEra |

    NSCalendarUnitYear |

    NSCalendarUnitMonth |

    NSCalendarUnitDay |

    NSCalendarUnitHour |

    NSCalendarUnitMinute |

    NSCalendarUnitSecond |

    NSWeekCalendarUnit |

    NSCalendarUnitWeekday |

    NSCalendarUnitWeekdayOrdinal |

    NSCalendarUnitQuarter;

    

    comps = [[NSCalendarcurrentCalendar] components:unitFlags fromDate:[NSDatedate]];

    [comps setHour:hour];

    [comps setMinute:minute];

    [comps setSecond:0];

    

    int temp = 0;

    int days = 0;

    

    temp = newWeekDay - components.weekday;

    days = (temp >= 0 ? temp : temp + 7);

    NSDate *newFireDate = [[[NSCalendarcurrentCalendar] dateFromComponents:comps] dateByAddingTimeInterval:3600 * 24 * days];

    return newFireDate;

 

}

你可能感兴趣的:(本地推送通知,自定义,星期,时间)