我正在构建一个iOS应用程序,它利用本地通知来提醒用户完成任务,但仅限于特定日期(由用户选择) . 通知应该触发的时间由日期选择器设置 . 我的代码基于另一个SO帖子中的一些代码 .
假设用户希望在周日完成所述任务 . 我要做的第一件事是找出当前日期是什么,并从中获取正确的组件,然后从日期选择器获取正确的组件,包括小时和分钟 .
//set up calendar and correct components
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now]; //get the required calendar units
NSDateComponents *pickedComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:picker.date];
NSDate *minuteHour = [calendar dateFromComponents:pickedComponents];
[[NSUserDefaults standardUserDefaults] setObject:minuteHour forKey:@"FireTime"];
NSString *reminder = @"Don't forget to check which customers are on vacation!";
接下来,保存数据,并设置通知 . 此代码对于一周中的每一天都是相同的,只更改了日期名称 .
当tempStatus等于“1”时,用户选择该日作为一天来提醒他们 .
//Save data
//sunday
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if ([sundayTempStatus isEqual:@"1"])
{
//permanently save the status
[[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"Sunday"];
//set up notifications
//if it is past sunday, push next week
if (components.weekday > 1)
{
components.weekOfYear++; //if already passed sunday, make it next sunday
}
components.hour = [pickedComponents hour];
components.minute = [pickedComponents minute];
NSDate *fireDate = [calendar dateFromComponents:components];
localNotification.fireDate = fireDate;
localNotification.alertBody = reminder;
localNotification.timeZone = [NSTimeZone systemTimeZone];
localNotification.repeatInterval = NSCalendarUnitWeekOfYear;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
else
{
[[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"Sunday"];
}
在此先感谢,如有必要,我很乐意提供更多信息和代码 .