如何在Xamarin.iOS(C#)中基于Firebase实现FCM推送通知?
Xamarin.iOS 集成 Firebase Cloud Messaging (FCM) 完整 AppDelegate.cs 实现
Hey there, I’ve been right where you are—struggling to get FCM push notifications working in a Xamarin.iOS app with Firebase backend. Let me share a complete, tested AppDelegate.cs implementation that should get you up and running, plus key tips to avoid common pitfalls.
Full AppDelegate.cs Code
using Foundation; using UIKit; using Firebase.Core; using Firebase.Messaging; namespace YourAppNamespace { [Register("AppDelegate")] public class AppDelegate : UIApplicationDelegate, IUNUserNotificationCenterDelegate, IMessagingDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // 初始化 Firebase 核心服务 Firebase.Core.App.Configure(); // 配置用户通知中心并请求权限 UNUserNotificationCenter.Current.Delegate = this; var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound; UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => { if (granted) { // 在主线程注册远程通知 InvokeOnMainThread(() => UIApplication.SharedApplication.RegisterForRemoteNotifications()); } }); // 设置 FCM Messaging 的代理 Messaging.SharedInstance.Delegate = this; // 处理从推送通知启动应用的情况(可选) if (launchOptions != null) { var remoteNotification = launchOptions[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary; if (remoteNotification != null) { HandleNotificationContent(remoteNotification); } } return true; } // 成功获取 APNs 设备令牌后,同步到 FCM public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken) { // 转换令牌格式:去掉尖括号和空格,适配 FCM 要求 var fcmToken = deviceToken.Description.Trim('<', '>').Replace(" ", ""); Messaging.SharedInstance.ApnsToken = deviceToken; // 这里可以将令牌发送到你的后端服务器保存,用于定向推送 System.Console.WriteLine($"FCM Device Token: {fcmToken}"); } // 注册远程通知失败的回调 public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error) { System.Console.WriteLine($"Failed to register for remote notifications: {error.LocalizedDescription}"); } // 应用在前台时接收通知的处理(控制是否显示横幅/声音/角标) [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")] public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, System.Action<UNNotificationPresentationOptions> completionHandler) { // 解析并处理通知内容 HandleNotificationContent(notification.Request.Content.UserInfo); // 设置前台显示通知的方式:同时显示横幅、播放声音、更新角标 completionHandler(UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound | UNNotificationPresentationOptions.Badge); } // 用户点击通知后的处理逻辑 [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")] public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, System.Action completionHandler) { // 解析并处理通知内容 HandleNotificationContent(response.Notification.Request.Content.UserInfo); // 必须调用完成回调 completionHandler(); } // 接收 FCM 数据消息的回调(即使应用在后台或终止状态) public void DidReceiveMessage(Messaging messaging, RemoteMessage remoteMessage) { System.Console.WriteLine($"Received FCM Data Message: {remoteMessage.AppData}"); // 处理数据消息内容 HandleNotificationContent(remoteMessage.AppData); } // 统一处理通知内容的私有方法 private void HandleNotificationContent(NSDictionary notificationData) { // 根据你的通知结构解析字段,这里是示例解析 title 和 body if (notificationData.TryGetValue(new NSString("title"), out NSObject titleObj) && notificationData.TryGetValue(new NSString("body"), out NSObject bodyObj)) { var title = titleObj.ToString(); var body = bodyObj.ToString(); System.Console.WriteLine($"Notification Received - Title: {title}, Body: {body}"); // 这里可以添加自定义逻辑:比如弹出弹窗、导航到指定页面等 } } } }
Critical Setup Notes
Don’t forget these steps—they’re the most common reasons FCM fails in Xamarin.iOS:
- Firebase Config File: Add
GoogleService-Info.plistto your project, set its Build Action toBundleResource(right-click the file in Solution Explorer -> Properties). - Required NuGet Packages: Install these via NuGet Package Manager:
Xamarin.Firebase.iOS.CoreXamarin.Firebase.iOS.MessagingXamarin.iOS.UserNotifications(usually installed automatically, but double-check)
- Apple Developer Portal Setup:
- Enable Push Notifications for your app ID.
- Generate and upload both Development and Production APNs certificates to the Firebase Console (Project Settings -> Cloud Messaging).
- Background Modes: Enable Remote notifications in your project’s
Info.plist(Visual Studio: Project Properties -> iOS Application -> Background Modes -> Check "Remote notifications"). - iOS Version Target: Make sure your deployment target is at least iOS 10.0—
UNUserNotificationCenterdoesn’t work on older versions.
内容的提问来源于stack exchange,提问作者mahmudamen
相关产品推荐
相关产品推荐

