每周特定日期的本地通知

Local Notification every specific day of week

我需要为一周中的每个工作日(不是周六和周日)触发的特定时间(例如 18:00)创建一个本地通知,但我找不到示例或教程。我想与 swift2.1 一起使用。如何创建此通知?我的问题是正确定义通知的触发日期

您可以使用 NSDateComponents 为本地通知创建准确的日期。这是示例,我们如何创建具有确切触发日期的本地通知:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday fromDate:now];//get the required calendar units

if (components.weekday>2) {
    components.weekOfYear+=1;//if already passed monday, make it next monday
}
components.weekday = 2;//Monday
components.hour = 11;
NSDate *fireDate = [calendar dateFromComponents:components];

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.alertBody = @"alert message";
localNotification.applicationIconBadgeNumber = 1;
localNotification.repeatInterval = NSCalendarUnitWeekOfYear;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

在这段代码中,我将触发日期设置为每周一 11 点 a.m,并使用本地通知 repeatInterval 将其设置为每周重复一次。代码可能有误,需要测试,但我想这给了你基本的想法,而且我没有在 swift 中编写代码,所以它是 objective c。希望这对您有所帮助!