Xamarin.Forms iOS中DidReceiveNotificationResponse未触发问题
Xamarin.Forms iOS本地通知点击无响应问题修复方案
你遇到的本地通知能正常显示,但点击后DidReceiveNotificationResponse完全不触发的问题,结合你的代码,可从以下几个方向排查修复:
1. 严格匹配Export选择器签名
iOS Objective-C选择器对格式要求极高,虽然你的Export字符串看起来正确,但可以尝试给completionHandler参数加上显式的Block代理标记,确保CLR类型到Objective-C的映射无误:
[Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")] public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, [BlockProxy(typeof(Action))] Action completionHandler) { if (response.IsDefaultAction) { if (response.Notification.Request.Content.UserInfo.ContainsKey(new NSString("remainingTime"))) { Locator.GetSharedInstance<IAlertDelayedService>().RaiseOpenAlertDelayedPopupEvent(); } } completionHandler(); }
2. 确保Delegate设置时机正确
把UNUserNotificationCenter.Current.Delegate = this;放在所有通知相关初始化代码的最前面,并且检查是否有第三方SDK或其他代码后续修改了这个Delegate。如果有其他推送相关组件,要保证AppDelegate的Delegate设置是最后一步。
3. 处理冷启动场景的通知点击
如果应用是完全关闭状态下点击通知启动,FinishedLaunching的options参数会携带通知信息,需要在这里额外处理:
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { Popup.Init(); global::Xamarin.Forms.Forms.Init(); // 先设置Delegate,再处理其他初始化 UNUserNotificationCenter.Current.Delegate = this; // 处理冷启动时的通知点击 if (options != null) { // 兼容iOS 10以下本地通知 if (options.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey)) { var localNotification = options[UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification; if (localNotification?.UserInfo != null && localNotification.UserInfo.ContainsKey(new NSString("remainingTime"))) { Locator.GetSharedInstance<IAlertDelayedService>().RaiseOpenAlertDelayedPopupEvent(); } } // iOS 10+冷启动通知处理 else if (options.ContainsKey(UIApplication.LaunchOptionsNotificationKey)) { var notification = options[UIApplication.LaunchOptionsNotificationKey] as UNNotification; if (notification?.Request.Content.UserInfo.ContainsKey(new NSString("remainingTime")) == true) { Locator.GetSharedInstance<IAlertDelayedService>().RaiseOpenAlertDelayedPopupEvent(); } } } LoadApplication(new App()); return base.FinishedLaunching(app, options); }
4. 清理缓存重新部署
Xamarin的绑定缓存偶尔会导致Delegate不生效,尝试:
- 执行清理解决方案操作
- 删除iOS项目下的bin和obj文件夹
- 重启开发工具后重新部署到设备或模拟器
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

