如何跳过第一次出现的重复 UNCalendarNotificationTrigger?

问题描述 投票:0回答:2

假设今天是星期一,下午 1 点。我想安排从今天下午 2 点开始每周通过我的 iOS 应用程序发出本地通知。我会这样做:

NSDateComponents *components = [[[NSDateComponents alloc]init]autorelease];
components.weekday = 2;
components.hour = 14;
components.minute = 0;

UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
//then make a UNMutableNotificationContent and UNNotificationRequest and schedule it

但是如果我想在周一下午 2 点开始下一个,我该如何跳过第一次出现?

以另一种方式问这个问题,如何安排在某个任意时间开始重复

UNCalendarNotificationTrigger
,而不是第一次出现重复间隔?

ios usernotifications
2个回答
0
投票

跳出框框思考。

您可以将服务器配置为在未来某个时间(即明天清晨)向您的手机发送静默推送通知。当您在后台收到推送通知时,您可以使用它来设置本地日历通知。这样您就可以有效地跳过第一个通知,或安排它们在将来的任何时间开始。

当然,您不应该完全依赖 APNS 网络,因此当应用程序处于前台时,您需要通过 API 调用来跟踪通知的状态。


0
投票

计算下周一下午 2 点的日期:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.weekday = 2;  // Monday (1 is Sunday)
components.hour = 14;    // 2 PM
components.minute = 0;

// Get the current date
NSDate *now = [NSDate date];

// Find the next Monday
NSDate *nextMonday = [calendar nextDateAfterDate:now
                           matchingComponents:components
                                  options:NSCalendarMatchNextTime];

使用计算出的日期创建 UNCalendarNotificationTrigger:

UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:[calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitWeekday)
                                                                                                      fromDate:nextMonday]
                                                                                                  repeats:YES];
© www.soinside.com 2019 - 2024. All rights reserved.