如何在Xamarin.Forms中实现通知(XAML/C#)?iOS是否支持?
在Xamarin.Forms中实现通知功能(含iOS平台支持说明)
嘿,我来帮你理清楚在Xamarin.Forms里实现通知的具体步骤,同时明确告诉你:iOS平台完全支持这些功能,不管是本地通知还是推送通知都没问题。下面分两种场景来讲解:
一、本地通知实现(用官方Xamarin.Essentials)
本地通知是不需要联网就能触发的提醒,Xamarin.Essentials已经帮我们封装好了跨平台的API,不用写太多原生代码。
1. 前期准备
- 先给你的Xamarin.Forms项目和各个平台项目安装
Xamarin.EssentialsNuGet包。 - iOS平台额外配置:权限可以直接通过代码请求,也可以在
Info.plist里提前配置相关描述。
2. C#代码实现(Xamarin.Forms共享项目中)
首先得请求用户授权,不然iOS会直接拦截通知:
using Xamarin.Essentials; async Task AskForNotificationPermission() { var permissionStatus = await Permissions.RequestAsync<Permissions.Notifications>(); if (permissionStatus != PermissionStatus.Granted) { // 这里可以提示用户去设置里开启权限 await Application.Current.MainPage.DisplayAlert("提示", "需要开启通知权限才能接收提醒", "知道了"); return; } }
然后发送一条本地通知,比如5秒后触发:
var notificationRequest = new NotificationRequest { Id = 1, // 唯一标识,用来取消通知用 Title = "你的待办事项", Description = "别忘了今天的会议!", Schedule = new NotificationSchedule { NotifyTime = DateTime.Now.AddSeconds(5) } }; // 调度通知 await Notifications.ScheduleAsync(notificationRequest);
3. 处理通知点击事件
如果想在用户点击通知时做些操作,比如跳转到特定页面,可以在App.xaml.cs里注册监听:
protected override void OnStart() { Notifications.Received += (sender, args) => { // UI操作必须在主线程执行 MainThread.BeginInvokeOnMainThread(() => { // 比如跳转到待办页面 Application.Current.MainPage.Navigation.PushAsync(new TodoPage()); // 或者弹个提示 Application.Current.MainPage.DisplayAlert("通知", args.Request.Description, "确定"); }); }; }
二、推送通知实现(以FCM为例,支持iOS)
如果需要给用户发送跨平台的推送通知,Firebase Cloud Messaging(FCM)是个不错的选择,iOS端会自动对接苹果的APNs服务。
1. 前期配置
- 给项目安装
Xamarin.Firebase.MessagingNuGet包。 - iOS端关键配置:
- 在Apple开发者后台生成APNs证书,上传到Firebase控制台。
- 在Xcode中给iOS项目启用
Push Notifications能力,同时开启Background Modes里的Remote notifications。 - 在
Info.plist里添加推送相关的权限描述。
2. iOS原生项目代码配置(AppDelegate.cs)
需要在iOS的AppDelegate里注册推送服务:
using Firebase.Messaging; using UserNotifications; public override bool FinishedLaunching(UIApplication app, NSDictionary options) { // 初始化Firebase Firebase.Core.App.Configure(); // 设置通知代理 UNUserNotificationCenter.Current.Delegate = this; // 请求通知权限 var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound; UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => { }); // 注册远程通知 UIApplication.SharedApplication.RegisterForRemoteNotifications(); return base.FinishedLaunching(app, options); } // 处理收到的推送消息 public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) { // 解析推送内容 var aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary; var alertDict = aps.ObjectForKey(new NSString("alert")) as NSDictionary; var title = alertDict.ObjectForKey(new NSString("title"))?.ToString(); var content = alertDict.ObjectForKey(new NSString("body"))?.ToString(); // 通过MessagingCenter把消息传给Xamarin.Forms共享项目 MessagingCenter.Send<object, (string Title, string Content)>(this, "PushReceived", (title, content)); completionHandler(UIBackgroundFetchResult.NewData); }
3. Xamarin.Forms共享项目接收推送
在App.xaml.cs里订阅消息,处理推送:
protected override void OnStart() { MessagingCenter.Subscribe<object, (string Title, string Content)>(this, "PushReceived", (sender, msg) => { MainThread.BeginInvokeOnMainThread(() => { Application.Current.MainPage.DisplayAlert("推送通知", $"{msg.Title}\n{msg.Content}", "确定"); }); }); }
三、iOS平台支持的关键注意点
再次确认:iOS平台完全支持Xamarin.Forms的通知功能,但要注意这些细节:
- iOS 10+必须通过
UNUserNotificationCenter请求权限,旧版框架已经被弃用了,Xamarin.Essentials和FCM都已经适配了新框架。 - 如果需要在后台接收推送,必须开启
Remote notifications后台模式,否则App在后台时可能收不到推送。 - 推送通知的证书配置一定要正确,不然iOS端会直接拒绝推送请求,这是很多开发者踩坑的地方。
- 本地通知在iOS上的显示样式可以自定义,比如添加按钮、图片,不过需要在iOS原生项目里配置扩展。
内容的提问来源于stack exchange,提问作者einerixcode
相关产品推荐
相关产品推荐

