如何在C#开发的Xamarin跨平台应用中显示iOS图标通知角标
Hey there! 我来给你讲讲怎么在Xamarin的iOS应用上实现图标角标(通知计数)的显示,这事儿其实挺 straightforward 的,有几种靠谱的方式,我给你拆解清楚:
直接用iOS原生API(Xamarin.iOS项目专属)
iOS的应用图标角标是通过UIApplication类直接控制的,这是最直接的实现方式,在你需要更新角标的地方调用以下代码就行:
// 设置角标数字为5 UIApplication.SharedApplication.ApplicationIconBadgeNumber = 5; // 清除角标(设置为0即可) UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
比如用户收到本地通知、查看消息后,都可以调用这段代码更新计数。
Xamarin.Forms跨平台实现(依赖服务)
如果你是做Xamarin.Forms跨平台项目,不想在每个平台写重复代码,可以用**依赖服务(DependencyService)**来封装,这样在共享代码里就能统一调用:
第一步:在共享项目定义接口
public interface IBadgeService { // 设置角标计数 void SetBadgeCount(int count); // 清除角标 void ClearBadge(); }
第二步:在iOS项目实现接口
[assembly: Dependency(typeof(BadgeService_iOS))] namespace YourAppNamespace.iOS { public class BadgeService_iOS : IBadgeService { public void SetBadgeCount(int count) { UIApplication.SharedApplication.ApplicationIconBadgeNumber = count; } public void ClearBadge() { UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; } } }
第三步:在共享代码里调用
// 设置角标为3 DependencyService.Get<IBadgeService>().SetBadgeCount(3); // 清除角标 DependencyService.Get<IBadgeService>().ClearBadge();
推送通知时设置角标
如果你的应用用APNs(苹果推送通知服务)推送消息,想要推送时自动更新角标,只需要在推送的payload里加上badge字段就行:
{ "aps": { "alert": "你有一条新消息!", "badge": 2, "sound": "default" } }
要是用第三方推送服务(比如Firebase Cloud Messaging、Azure Notification Hubs),记得在发送推送时配置badge参数。
另外,如果你需要在收到推送后手动处理角标,可以在iOS项目的AppDelegate里重写DidReceiveRemoteNotification方法:
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler) { var aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary; if (aps != null) { var badgeCount = aps.ObjectForKey(new NSString("badge")) as NSNumber; if (badgeCount != null) { UIApplication.SharedApplication.ApplicationIconBadgeNumber = badgeCount.Int32Value; } } completionHandler(UIBackgroundFetchResult.NewData); }
关键注意事项
- 权限申请:iOS 10及以上版本必须先获取用户的通知权限,否则角标不会显示,你需要在
AppDelegate的FinishedLaunching方法里添加权限请求代码:
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { // 请求通知权限(包含角标权限) if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) { UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Badge | UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound, (granted, error) => { if (granted) { InvokeOnMainThread(() => UIApplication.SharedApplication.RegisterForRemoteNotifications()); } }); } else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound, null); UIApplication.SharedApplication.RegisterUserNotificationSettings(settings); UIApplication.SharedApplication.RegisterForRemoteNotifications(); } // 其他初始化代码... return true; }
- 同步更新:角标数字是全局的,用户查看所有未读消息后一定要记得清零,不然会一直显示旧的计数。
- 后台限制:如果想在后台更新角标,确保应用有对应的后台权限,不过一般推送通知触发的更新,系统会自动处理。
内容的提问来源于stack exchange,提问作者srinivas challa
相关产品推荐
相关产品推荐

