无法将待处理本地通知保存至数组的技术问题求助
问题分析与解决方案
问题根源
UNUserNotificationCenter.getPendingNotificationRequests(_:)是异步方法,其闭包会在后台队列执行。你在闭包外部直接访问test数组时,闭包内的append操作还未完成,因此数组看起来是空的——调试器能看到通知是因为闭包最终确实执行了,但你的代码没有等待闭包完成就去访问数组。
解决方案
方案1:使用闭包回调处理结果
通过自定义回调闭包,确保在通知请求获取完成后再处理数据:
let center = UNUserNotificationCenter.current() // 封装获取逻辑 func getPendingNotifications(completion: @escaping ([UNNotificationRequest]) -> Void) { center.getPendingNotificationRequests { pendingRequests in completion(pendingRequests) } } // 调用示例 getPendingNotifications { notifications in // 在这里处理获取到的通知数组,比如赋值给需要的变量 print("共获取到 \(notifications.count) 个待调度通知") // 所有依赖通知数组的逻辑都要放在这个闭包里 }
方案2:使用Swift async/await(iOS 15+)
如果你的项目支持iOS 15及以上,用异步等待语法会更简洁直观:
let center = UNUserNotificationCenter.current() // 封装异步获取方法 func fetchPendingNotifications() async -> [UNNotificationRequest] { await center.pendingNotificationRequests() } // 在异步上下文调用(比如Task内) Task { let notifications = await fetchPendingNotifications() print("共获取到 \(notifications.count) 个待调度通知") // 在这里处理通知数组 }
关键提醒
不要尝试在闭包外部直接同步访问异步方法返回的数据,必须等待异步操作完成后再进行后续逻辑处理——这是iOS异步API的核心使用原则。
内容的提问来源于stack exchange,提问作者rhun14
相关产品推荐
相关产品推荐

