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

iOS平台点击通知操作按钮后如何获取并保存通知内容?

解决iOS通知按钮点击后获取标题/正文并保存的问题

嘿,这事儿其实挺简单的,咱们直接看怎么实现:

首先,UNNotificationResponse 对象里已经包含了你需要的所有通知信息,你只需要从它的 notification.request.content 属性里拿到通知的标题和正文就行。下面是修改后的完整代码:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // 先取出通知的核心内容对象
    let notificationContent = response.notification.request.content
    
    if response.actionIdentifier == "Yes" {
        // 将通知正文保存到Content变量(这里是局部变量,如需全局使用可以定义类属性)
        let content = notificationContent.body
        // 这里可以加你需要的后续操作,比如打印、存到UserDefaults或者其他地方
        print("已保存通知正文:\(content)")
    } else {
        // 将通知标题保存到Title变量
        let title = notificationContent.title
        print("已保存通知标题:\(title)")
    }
    
    scheduleNotification()
    completionHandler()
}

补充说明:

  • 如果需要在方法外部访问这些变量,建议在你的类里先定义对应的属性,比如:
    class YourNotificationHandlerClass: NSObject, UNUserNotificationCenterDelegate {
        var savedContent: String?
        var savedTitle: String?
        
        // 然后在didReceive方法里赋值
        if response.actionIdentifier == "Yes" {
            savedContent = notificationContent.body
        } else {
            savedTitle = notificationContent.title
        }
    }
    
  • notificationContent.body 就是通知的正文内容,notificationContent.title 是通知的标题,不管通知内容怎么变化,这两个属性都会对应最新的通知数据。

内容的提问来源于stack exchange,提问作者deexno

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:16:45