如何访问UNNotificationContent标题以展示待处理本地通知
问题:日历触发本地通知提交后回读content字段为空
问题复现代码
开发日历触发本地通知功能时的实现代码如下:
func CalendarTriggeredNotification(givenDate: Date, roomName: String, itemName: String) { let content = UNMutableNotificationContent() content.title = "Freshness Check." content.subtitle = "Room: \(roomName). Check on \(itemName)" content.sound = UNNotificationSound.default let dateComponent = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute], from: givenDate) let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) UNUserNotificationCenter.current().getPendingNotificationRequests { requests in print(requests) } successNotificationBanner(title: "Reminder Saved") }
异常现象
调用getPendingNotificationRequests打印待发送通知的结果如下:
[<UNNotificationRequest: 0x600003c502a0; identifier: 62F8BB2B-FC5D-40AE-8C43-6AFEEFBD9F0B, content: <UNNotificationContent: 0x600000ee6a00; title: , subtitle: , body: (null), summaryArgument: , summaryArgumentCount: 0, categoryIdentifier: , launchImageName: , threadIdentifier: , attachments: ( ), badge: (null), sound: <UNNotificationSound: 0x6000019df170>, realert: 0, interruptionLevel: 1, relevanceScore: 0.00, trigger: <UNCalendarNotificationTrigger: 0x6000033efe40; dateComponents: <NSDateComponents: 0x6000030e8330> { Calendar Year: 2022 Month: 7 Day: 11 Hour: 11 Minute: 49, repeats: NO>>]
返回结果中UNNotificationContent的title、subtitle字段显示为脱敏空值,无法直接读取用于展示待发送的本地通知列表。
原因说明
这是iOS系统的隐私安全设计,不是代码逻辑错误:
当你把UNNotificationRequest通过add(_:)方法提交给系统通知中心后,系统会接管通知的调度和发送,后续通过getPendingNotificationRequests回调返回的请求对象,会对所有通知文本内容(title、subtitle、body、附带的自定义userInfo敏感字段)做脱敏处理,不会返回原始值。
你设置的通知内容实际是生效的,到达触发时间时通知会正常展示你预设的标题和副标题,只是系统不允许第三方App回读已经提交到通知中心的内容文本。
解决方案
不要尝试从系统返回的UNNotificationRequest对象中读取通知文本内容,可通过以下两种方式实现待发送通知的展示需求:
- 本地持久化通知业务数据
创建通知请求时,自行生成唯一的request identifier,将identifier、触发时间、通知标题、副标题、关联的业务参数(如示例中的roomName、itemName)同步存储到本地(可选UserDefaults、Core Data、沙盒文件等任意本地存储方案)。需要展示待发送通知列表时,先拉取系统返回的pending requests获取触发时间、重复规则等非脱敏字段,再通过identifier匹配你本地存储的文本内容和业务数据即可。 - 提交前暂存内容快照
如果不需要持久化,可在调用add(_:)提交通知请求之前,提前把通知的所有展示字段、触发规则暂存到当前作用域或内存缓存中,后续需要展示时直接使用暂存的副本即可。
注意:不要通过runtime、反射等手段尝试读取系统脱敏后的私有字段,这类操作属于私有API调用,会触发App Store审核拒审,且不同iOS系统版本的内部字段结构无稳定性保障,线上容易出现兼容问题。
内容的提问来源于stack exchange,提问作者user7894007
相关产品推荐
相关产品推荐

