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

如何将UNUserNotificationCenter获取的通知标题填入TextField?

解决UNUserNotificationCenter获取待处理通知并填入TextField的闭包错误问题

嘿,这个坑我之前也踩过!你遇到的错误是因为getPendingNotificationRequests(completionHandler:)的闭包签名没写对——这个方法的完成闭包必须接收一个[UNNotificationRequest]类型的参数,但你的代码里要么没声明这个参数,要么闭包的写法让编译器误以为它应该是一个无参数的() -> Void闭包,所以才会报“期望0个参数,但用了1个”的错误。

正确的实现步骤&代码示例

下面是完整的正确代码,我会标注关键注意点:

// 1. 获取通知中心实例
let notificationCenter = UNUserNotificationCenter.current()

// 2. 调用getPendingNotificationRequests,传入正确的闭包
notificationCenter.getPendingNotificationRequests { pendingRequests in
    // 3. 从待处理请求中提取标题(这里以取第一个请求的标题为例)
    let targetTitle = pendingRequests.first?.content.title ?? "无待处理通知"
    
    // 4. 必须切换到主线程更新UI!因为完成闭包是在后台线程执行的
    DispatchQueue.main.async {
        // 把标题填入你的TextField,替换成你实际的TextField变量名
        self.yourTextField.text = targetTitle
    }
}

如果你需要处理多个通知的情况

如果要把所有待处理通知的标题都拼起来填入TextField,可以改成这样:

notificationCenter.getPendingNotificationRequests { pendingRequests in
    let allTitles = pendingRequests.map { $0.content.title }.joined(separator: " | ")
    
    DispatchQueue.main.async {
        self.yourTextField.text = allTitles.isEmpty ? "无待处理通知" : allTitles
    }
}

为什么之前的代码会报错?

举个常见的错误写法,你可能是这样写的(编译器会判定闭包是() -> Void,但你在里面用了参数):

// ❌ 错误示例:闭包没声明参数,但在内部使用了pendingRequests
notificationCenter.getPendingNotificationRequests {
    print(pendingRequests.count) // 这里编译器会报错,因为它认为这个闭包不该有参数
}

只要在闭包开头明确声明参数(比如pendingRequests in),就能让编译器正确识别闭包的类型,解决这个错误。

内容的提问来源于stack exchange,提问作者Final Fantassy Remix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:07:28