Local Notification every specific day of week

戏子无情 提交于 2020-01-23 02:38:11

问题


I need to create a local notification for a specific time (example at 18.00) fired every working day of week (not Saturday and Sunday) but I can't find examples or tutorial. I want use with swift2.1. How can I create this notification? My problem is define the firedate correctly of the notification


回答1:


You can use NSDateComponents to create the exact date for your local notification. Here is the example, how do we create local notification with exact fire date:

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];

In this piece of code, I set the fire date to every Monday 11 a.m, and set it repeat weekly using repeatInterval of local notification. Code maybe wrong, need to test, but I guess this gives you the basic idea, also I don't code in swift, so it's objective c. Hope this helps!



来源:https://stackoverflow.com/questions/35101186/local-notification-every-specific-day-of-week

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!