You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取本地通知待处理请求时遇函数类型转换错误求助

解决UNUserNotificationCenter闭包抛出类型不匹配的错误

这个错误的核心原因很明确:你传给getPendingNotificationRequests(completionHandler:)的闭包里包含了未处理的抛出操作,导致闭包类型变成了(_) throws -> Void,但系统要求这个completionHandler必须是一个非抛出的([UNNotificationRequest]) -> Void类型,两者不兼容所以触发了报错。

修复方案:处理闭包内的抛出代码

你需要把闭包里所有可能抛出异常的代码用do-catch块包裹,或者用try?/try!来处理错误,让闭包回到非抛出类型。

示例1:用do-catch优雅处理错误

如果需要捕获并处理错误,推荐这种方式:

var notificationTitle = "\(String(describing: notificationData!["title"]))"
var notificationInterval: Int = notificationData!["interval"] as! Int
let center = UNUserNotificationCenter.current()

center.getPendingNotificationRequests(completionHandler: { requests in
    do {
        // 这里放你原本会抛出错误的代码,比如移除指定通知请求
        try center.removePendingNotificationRequests(withIdentifiers: ["your-notification-id"])
        
        // 其他业务逻辑,比如遍历待处理请求做判断
        for request in requests {
            print("待处理通知ID:\(request.identifier)")
        }
    } catch {
        // 捕获并处理错误,避免崩溃
        print("处理通知请求时出错:\(error.localizedDescription)")
    }
})

示例2:用try?忽略错误(适合不需要处理错误的场景)

如果不需要关心错误结果,可以用try?把抛出操作转为可选值,这样不会传播错误:

var notificationTitle = "\(String(describing: notificationData!["title"]))"
var notificationInterval: Int = notificationData!["interval"] as! Int
let center = UNUserNotificationCenter.current()

center.getPendingNotificationRequests(completionHandler: { requests in
    // 用try?忽略错误,代码不会抛出异常
    try? center.removePendingNotificationRequests(withIdentifiers: ["your-notification-id"])
    
    // 后续逻辑,比如筛选特定通知请求
    let targetRequests = requests.filter { $0.identifier == "target-id" }
    // ...
})

额外建议:避免强制解包提升代码安全性

你的代码里用了notificationData!这种强制解包,很容易导致运行时崩溃,建议用可选绑定来处理:

guard let notificationData = notificationData,
      let title = notificationData["title"] as? String,
      let interval = notificationData["interval"] as? Int else {
    // 处理数据为空或类型转换失败的情况,比如打印日志或直接返回
    print("通知数据无效,无法继续处理")
    return
}
let notificationTitle = title
let notificationInterval = interval

// 后续的通知中心操作...

内容的提问来源于stack exchange,提问作者Keshav.K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:14:32