过去某个日期的 NSNotifications

NSNotifications For A Date In The Past

我正在编写一个应用程序,其中有很多基于过去的日期。例如,周年纪念日。假设这个日期是 2000 年 12 月 25 日。

用户从日期选择器中选择该日期,然后该日期将保存到用户的设备中。 (假设保存的日期是 2000 年 12 月 25 日)

在思考我将如何编写 NSNotifications 代码时,我意识到我最大的任务(现在看来是不可能的)是我如何能够向用户发送一个未来日期的提醒,但基于过去的某个日期。

示例:
周年纪念日是 2000 年 12 月 25 日

每年 12 月 25 日提醒用户。

我想一定有办法,但我的搜索却空手而归。

不确定您使用的是什么语言,但这里的基本逻辑是一旦用户选择了日期,就关闭日期设置本地通知,然后将重复设置为 kCFCalendarUnitYear

objective-C

中的示例代码
-(void)setAlert:(NSDate *)date{
    //Note date here is the closest anniversary date in future you need to determine first
    UILocalNotification *localNotif = [[UILocalNotification alloc]init];
    localNotif.fireDate = date;
    localNotif.alertBody = @"Some text here...";
    localNotif.timeZone = [NSTimeZone defaultTimeZone]; 
    localNotif.repeatInterval = kCFCalendarUnitYear; //repeat yearly
    //other customization for the notification, for example attach some info using 
    //localNotif.userInfo = @{@"id":@"some Identifier to look for more detail, etc."};
   [[UIApplication sharedApplication]scheduleLocalNotification:localNotif];
}

设置警报并触发警报后,您可以通过实施

AppDelegate.m 文件中处理通知
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void(^)())completionHandler{
    //handling notification code here.
}

编辑:

关于如何获得最接近的日期,您可以实现一个方法来做到这一点

-(NSDate *) closestNextAnniversary:(NSDate *)selectedDate {
    // selectedDate is the old date you just selected, the idea is extract the month and day component of that date, append it to the current year, if that date is after today, then that's the date you want, otherwise, add the year component by 1 to get the date in next year
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger month = [calendar component:NSCalendarUnitMonth fromDate:selectedDate];
    NSInteger day = [calendar component:NSCalendarUnitDay fromDate:selectedDate];
    NSInteger year = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    NSDate *targetDate = [calendar dateFromComponents:components];
    // now if the target date is after today, then return it, else add one year 
    // special case for Feb 29th, see comments below 
    // your code to handle Feb 29th case.
    if ([targetDate timeIntervalSinceDate:[NSDate date]]>0) return targetDate;
    [components setYear:++year];
    return [calendar dateFromComponents:components];
}

你需要考虑的一件事是如何对待2月29日,是每年2月28日(非闰年)报警,还是每四年报警一次?然后你需要实现自己的逻辑。