MAUI iOS平台FCM推送通知配置疑问及Token生成确认
MAUI iOS 适配Plugin.Firebase推送通知配置说明
已完成配置回顾
你已经完成了iOS推送的基础配置:
- 在苹果开发者后台为App ID开启Push Notification服务
- 创建并安装了包含推送权限的配置文件,绑定到项目
- 生成P8密钥并上传至FCM控制台,填写了Team Id和Key Id
待完成配置的具体操作
1. 在Info.plist中启用Remote Notification
MAUI没有可视化的Capabilities标签,直接手动编辑Platforms/iOS/Info.plist,添加以下内容:
<key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array>
这一步是开启后台推送权限,确保应用在后台状态下能接收推送消息。
2. 创建并配置Entitlements.plist
MAUI默认不生成该文件,需手动创建并配置:
- 在解决方案资源管理器中,右键点击
Platforms/iOS文件夹 → 添加 → 新建项 - 选择「Property List」模板,命名为
Entitlements.plist并创建 - 打开该文件,点击「+」添加新键,输入
aps-environment,类型选择「String」,值根据环境选择:- 开发环境填
development - 生产环境填
production
- 开发环境填
- 最后在项目属性的iOS页签中,找到「自定义权利」选项,选择刚创建的
Entitlements.plist文件
FCM Token生成的额外必要步骤
完成上述两项配置后,还需要以下操作才能正常生成FCM Token:
- 请求用户通知权限:iOS要求必须获得用户授权才能获取推送令牌,在App启动阶段添加权限请求代码:
using UserNotifications; // 可放在App.xaml.cs的OnStart或Platforms/iOS/AppDelegate的FinishedLaunching方法中 var notificationCenter = UNUserNotificationCenter.Current; await notificationCenter.RequestAuthorizationAsync(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound); UIApplication.SharedApplication.RegisterForRemoteNotifications();
- 在AppDelegate中同步APNs令牌到FCM:
打开Platforms/iOS/AppDelegate.cs,重写以下方法:
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken) { CrossFirebaseCloudMessaging.Current.RegisterAPNsToken(deviceToken); } public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error) { Console.WriteLine($"APNs注册失败: {error.LocalizedDescription}"); }
- 确保Firebase初始化顺序正确:
在Platforms/iOS/AppDelegate.cs的FinishedLaunching方法中,优先执行Firebase初始化代码:
Firebase.Core.App.Configure();
调整后的FCM Token获取函数
结合iOS权限要求,修改Token获取逻辑,建议在权限请求成功后调用:
private async Task GetTokenAsync() { try { await CrossFirebaseCloudMessaging.Current.CheckIfValidAsync(); var token = await CrossFirebaseCloudMessaging.Current.GetTokenAsync(); Preferences.Default.Set("devicefcmtoken", token); Console.WriteLine($"FCM token::>> {token}"); } catch (Exception ex) { Console.WriteLine($"获取FCM Token失败: {ex.Message}"); } }
内容的提问来源于stack exchange,提问作者Matthew Pans
相关产品推荐
相关产品推荐

