检查通知权限是否被授予(Xamarin,iOS)

agyaoht7  于 2023-05-27  发布在  iOS
关注(0)|答案(4)|浏览(152)

系统将提示用户拒绝/授予通知权限:
screenshot
该应用程序有一个设置视图,用户可以在其中切换通知。如果权限未被授予,我希望将用户指向iOS设置(就像WhatsApp一样)。
如何检查是否已授予权限?特别是当用户赠款权限,但随后决定从iOS设置中禁用它们时,而不是在应用程序内。
有一个非常流行的permissions plugin,它不支持这个特定的权限。

hc2pp10m

hc2pp10m1#

您可以使用DependencyService检查是否为应用启用了通知。
在iOS中:

[assembly: Dependency(typeof(DeviceService))]
  class DeviceService : IDeviceService
  {
    public bool GetApplicationNotificationSettings()
     {
     var settings = UIApplication.SharedApplication.CurrentUserNotificationSettings.Types;
            return settings != UIUserNotificationType.None;
     }
   }

形式:

public interface IDeviceService
{
   bool GetApplicationNotificationSettings();
}

在这些之后,您可以从您的页面或视图模型调用DependencyService,如下所示:

bool isNotificationEnabled = DependencyService.Get<IDeviceService>().GetApplicationNotificationSettings();
vddsk6oq

vddsk6oq2#

基本上,您需要在每个应用程序运行时请求授权。因此,如果你需要的话,你可以知道授权状态,并将用户导航到你的应用的ios设置。

UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (approved, error) =>
            {
                // do something with approved
                // approved will be true if user given permission or false if not
            });

如果该方法被赋予了权限,则该方法将在每次运行时返回true。如果它改变了,它将返回false。

hgtggwj0

hgtggwj03#

试试这个:

Device.OpenUri(new Uri("app-settings:"));

或者你可以这样做(对于Android和iOS):https://dotnetco.de/open-app-settings-in-xamarin-forms/

erhoui1w

erhoui1w4#

更全面的通知设置检查:

var Notificationssettings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync();
switch (Notificationssettings.AuthorizationStatus)
{
    case UNAuthorizationStatus.Authorized:
        return true;
    case UNAuthorizationStatus.Denied:
        return false;
    case UNAuthorizationStatus.Ephemeral:
        return true;
    case UNAuthorizationStatus.NotDetermined:
        return false;
    case UNAuthorizationStatus.Provisional:
        return true;
    default:
        return false;
}

相关问题