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

iOS点击通知后如何在App.cs的OnResume方法中获取RequestId值

实现说明

该需求可以实现,具体操作步骤如下:

  • 第一步:修改通知创建代码,将RequestId存入通知自定义字段
    在你构造UNMutableNotificationContent的代码块中,新增UserInfo赋值逻辑,把RequestId存入通知的自定义参数里:
var content = new UNMutableNotificationContent();
content.Title = item.Text;
content.Body = item.Description;
content.Badge = 1;
// 新增代码:存储RequestId到通知属性
content.UserInfo = new NSDictionary(
    new NSString("NotificationRequestId"), 
    new NSString(requestID)
);
  • 第二步:在iOS项目AppDelegate中实现通知点击回调
    首先为AppDelegate添加IUNUserNotificationCenterDelegate接口,在FinishedLaunching方法中注册通知代理:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();
    LoadApplication(new App());
    // 注册通知回调代理
    UNUserNotificationCenter.Current.Delegate = this;
    return base.FinishedLaunching(app, options);
}

然后实现通知点击的响应方法,将获取到的RequestId存入全局存储:

[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
{
    // 从点击的通知中取出之前存储的RequestId
    var requestId = response.Notification.Request.Content.UserInfo
        .ObjectForKey(new NSString("NotificationRequestId"))?.ToString();
    if (!string.IsNullOrEmpty(requestId))
    {
        // 存入Xamarin.Forms全局属性池,供共享层App.cs读取
        Xamarin.Forms.Application.Current.Properties["ClickedNotificationReqId"] = requestId;
    }
    completionHandler();
}
  • 第三步:在App.cs的OnResume方法中读取RequestId
protected override void OnResume()
{
    // 读取点击通知传入的RequestId
    if (Properties.ContainsKey("ClickedNotificationReqId"))
    {
        var targetRequestId = Properties["ClickedNotificationReqId"].ToString();
        // 此处编写拿到RequestId后的业务逻辑
        
        // 读取完成后删除存储,避免下次触发OnResume重复读取
        Properties.Remove("ClickedNotificationReqId");
    }
}

补充说明

如果应用处于完全杀死状态时用户点击通知启动,你需要额外在FinishedLaunching方法中判断启动参数options是否包含通知数据,同步将RequestId存入全局属性,避免该场景下无法获取参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:21:02