如何在UNNotificationRequest中配置起止时间实现本地通知调度
基于UNNotificationRequest实现指定起止时间的本地通知调度方案
该需求完全可以通过UNNotificationRequest实现,UNNotificationRequest本身没有原生的结束时间配置参数,需要通过「触发条件配置+主动移除待调度通知」的组合逻辑实现完整需求,具体操作步骤如下:
- 第一步:构造通知基础内容
初始化UNMutableNotificationContent实例,配置通知的标题、正文、提示音、附加信息等基础属性,示例代码框架:UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.title = @"提醒标题"; content.body = @"通知正文内容"; content.sound = [UNNotificationSound defaultSound]; - 第二步:配置指定开始时间的触发条件
使用UNCalendarNotificationTrigger匹配你需要的开始时间,将指定的开始年月日时分等参数拆解为NSDateComponents实例,生成对应的触发条件:
如果是需要按周期重复的通知(比如每日固定时间提醒),将// 示例:指定2024年10月1日8:00触发 NSDateComponents *components = [[NSDateComponents alloc] init]; components.year = 2024; components.month = 10; components.day = 1; components.hour = 8; UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];repeats参数设置为YES即可。 - 第三步:匹配结束时间逻辑
根据通知类型做不同处理:- 单次通知:仅触发一次,无需额外处理结束时间,配置正确的开始触发时间即可。
- 周期重复通知:提前记录该通知的唯一标识ID,同时注册一个对应结束时间的定时任务,到结束时间点调用系统接口移除还未触发的待调度通知:
// 结束时间到达时执行该代码,移除对应待调度通知 [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[你的通知唯一ID]];
- 第四步:生成并提交通知请求
绑定通知ID、内容、触发条件生成UNNotificationRequest实例,提交到系统通知中心即可:NSString *notificationId = @"你自定义的唯一通知标识"; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:notificationId content:content trigger:trigger]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
注意:通知的唯一标识ID必须提前持久化记录,后续移除待调度通知时需要精准匹配该ID,避免误删其他应用内通知
内容的提问来源于stack exchange,提问作者Avinash Tag
相关产品推荐
相关产品推荐

