MASA MAUI Plugin (七)应用通知角标(小红点)Android+iOS

背景

MAUI的出现,赋予了广大Net开发者开发多平台应用的能力,MAUI 是Xamarin.Forms演变而来,但是相比Xamarin性能更好,可扩展性更强,结构更简单。但是MAUI对于平台相关的实现并不完整。所以MASA团队开展了一个实验性项目,意在对微软MAUI的补充和扩展,项目地址https://github.com/BlazorComponent/MASA.Blazor/tree/feature/Maui/src/Masa.Blazor.Maui.Plugin,每个功能都有单独的demo演示项目,考虑到app安装文件体积(虽然MAUI已经集成裁剪功能,但是该功能对于代码本身有影响),届时每一个功能都会以单独的nuget包的形式提供,方便测试,现在项目才刚刚开始,但是相信很快就会有可以交付的内容啦。

前言

本系列文章面向移动开发小白,从零开始进行平台相关功能开发,演示如何参考平台的官方文档使用MAUI技术来开发相应功能。

介绍

上一篇文章我们集成了个推的消息通知,那么消息到达移动端之后,除了会在通知栏显示之外,在应用的角标也会显示未读消息的数量(小红点),然后用户点击查看消息之后,这些数字角标也可以自动消除,这个功能在MAUI中如何实现呢。

一、iOS部分

思路

https://developer.apple.com/documentation/uikit/uiapplication/1622918-applicationiconbadgenumber

我们参考一下官方文档,UIApplication下有一个applicationIconBadgeNumber的属性

var applicationIconBadgeNumber: Int {
    get set }

我们只需要给这个属性赋值具体的整数即可,

https://developer.apple.com/documentation/uikit/uiapplication/1622975-shared

我们可以通过shared获取当前UIApplication的实例,然后就可以给applicationIconBadgeNumber赋值了,但是如果你直接这样做,你会发现并没有效果,因为 iOS 8 以后,需要注册用户通知,以获得用户的授权。

https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649527-requestauthorization

我们可以通过UNUserNotificationCenterRequestAuthorization方法获取请求用户本地和远程的通知权限。
在这里插入图片描述

开发步骤

我们新建一个目录Badger,并在下面新建MAUI类库项目Masa.Blazor.Maui.Plugin.Badger
Platforms下的iOS文件夹新建MasaMauiBadgerService部分类

using UIKit;
using UserNotifications;
namespace Masa.Blazor.Maui.Plugin.Badger
{
   
	public static partial class MasaMauiBadgerService
	{
   
        private static void PlatformSetNotificationCount(int count)
		{
   
			// Requests the user’s authorization to allow local and remote notifications for your app.
			UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Badge, (r, e) =>{
   });
			
			// The number currently set as the badge of the app icon on the Home screen
			// Set to 0 (zero) to hide the badge number. The default value of this property is 0.
			UIApplication.SharedApplication.ApplicationIconBadgeNumber = count;
		}
	}
}

RequestAuthorization方法有两个参数

1、UNAuthorizationOptions 代表应用请求的授权选项,这里我们使用Badge
2、completionHandle 这是一个Action,有两个参数,第一个参数是一个bool值,代表是否已授予授权,第二个参数是一个NSError类型,表示包含错误信息或未发生错误的对象。我们这里暂不处理出错的情况

我们通过UIApplication.SharedApplication获取当前的UIApplication实例,然后直接给
ApplicationIconBadgeNumber 赋值,这里如果我们想清除角标,就直接赋值0即可。
我们继续在项目根目录新建MasaMauiBadgerService类,通过SetNotificationCount来调用不同平台的PlatformSetNotificationCount方法。

namespace Masa.Blazor.Maui.Plugin.Badger
{
   
    // All the code in this file is included in all platforms.
    public static partial class MasaMauiBadgerService
    {
   
        public static void SetNotificationCount(int count
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值