每周特定日期的本地通知

时间:2016-01-30 11:25:56

标签: ios notifications swift2 ios9 uilocalnotification

我需要在一周的每个工作日(不是星期六和星期日)发布特定时间(例如18.00)的本地通知,但我找不到示例或教程。我想用swift2.1。我该如何创建此通知?我的问题是正确定义通知的被激活者

1 个答案:

答案 0 :(得分:8)

您可以使用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点,并使用repeatInterval本地通知将其设置为每周重复一次。代码可能不对,需要测试,但我想这给了你基本的想法,我也不用swift编码,所以这是客观的c。希望这有帮助!