Xamarin.iOS前台接收FCM远程通知自定义横幅不显示问题排查
Xamarin.iOS FCM前台自定义横幅不显示的问题排查与修复
可能的问题及修复方案
1. iOS 13+ 中 KeyWindow 已弃用,无法获取正确窗口
在iOS 13及以上版本,UIApplication.SharedApplication.KeyWindow 已被标记为弃用,尤其是应用采用Scene架构时,直接调用可能返回null或非当前活跃窗口,导致自定义横幅无法添加到正确视图层级。
修复代码:
// 替换原获取window的逻辑 var window = UIApplication.SharedApplication.ConnectedScenes .OfType<UIWindowScene>() .FirstOrDefault()?.Windows .FirstOrDefault(w => w.IsKeyWindow); // 兼容旧版本 fallback if (window == null) { window = UIApplication.SharedApplication.KeyWindow; }
2. 自定义 NotificationBannerView 缺少可见样式设置
你的自定义横幅视图可能未设置背景色、文字颜色等属性,导致横幅已添加但因样式问题不可见。需完善NotificationBannerView的初始化逻辑:
public class NotificationBannerView : UIView { public UILabel TitleLabel { get; set; } public UILabel MessageLabel { get; set; } public NotificationBannerView(CGRect frame) : base(frame) { // 设置背景色确保可见 BackgroundColor = UIColor.FromRGB(50, 50, 50); TitleLabel = new UILabel { Frame = new CGRect(15, 12, frame.Width - 30, 24), TextColor = UIColor.White, Font = UIFont.BoldSystemFontOfSize(16) }; AddSubview(TitleLabel); MessageLabel = new UILabel { Frame = new CGRect(15, 40, frame.Width - 30, 20), TextColor = UIColor.LightGray, Font = UIFont.SystemFontOfSize(14) }; AddSubview(MessageLabel); } }
3. 视图层级被覆盖,横幅显示在底层
即使添加到窗口,横幅也可能被导航栏、TabBar或其他视图覆盖。需确保横幅处于视图层级最顶层:
// 替换window.AddSubview(bannerView)为: window.RootViewController.View.AddSubview(bannerView); // 强制设置层级优先级 bannerView.Layer.ZPosition = float.MaxValue;
4. 确认事件触发与服务实例有效性
虽然你能在输出中看到消息,但仍需验证事件是否正确触发、服务实例是否获取成功:
private void Current_OnNotificationReceived(object source, FirebasePushNotificationDataEventArgs e) { Console.WriteLine("[FCM] 前台收到通知"); var notificationService = DependencyService.Get<INotificationService>(); if (notificationService == null) { Console.WriteLine("[错误] INotificationService 实例为null"); return; } Device.BeginInvokeOnMainThread(() => { // 从FCM数据中解析真实标题和内容,而非硬编码值 var title = e.Data.TryGetValue("title", out var t) ? t.ToString() : "通知"; var message = e.Data.TryGetValue("body", out var b) ? b.ToString() : "新消息"; notificationService.ShowNotification(title, message); }); }
内容的提问来源于stack exchange,提问作者rana hd
相关产品推荐
相关产品推荐

