Custom local push notification (UILocalNotification) week and time

 

//create local notification

UILocalNotification * localNote = [[ UILocalNotification alloc ] init ];

//custom (week and time)

NSDate * newDate = [ self getNextWeekDay : 2 hour : 20 minutes : 25 ];

    self.localNote.fireDate = newDate;

//Set the repetition period to: week ( if the attribute NSCalendarUnitDay or NSCalendarUnitWeekDay is used repeatedly every day)

    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 = @" New notification ~~!" ;

//    Remove old notifications to prevent repeated additions

    [[UIApplicationsharedApplication] cancelAllLocalNotifications];

 

    [[UIApplicationsharedApplication] scheduleLocalNotification:self.localNote];

 

/**

 *  Get the next new day of the week

 *

 *  @param newWeekDay week value counts from Sunday , Sunday 1/ Monday 2/ Tuesday 3... Saturday 7

 *  The hour value set by @param hour      

 *  The minute value set by @param minute    

 *

 *  @return returns the new date (NSDate object )

 */

 

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

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

    

    HTLog ( @" set 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;

 

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327040241&siteId=291194637