简体   繁体   English

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

[英]Check if notification permission got granted (Xamarin, iOS)

The user is prompted to deny/grant permission for notifications:提示用户拒绝/授予通知权限:

screenshot截屏

The app has a settings view where the user can toggle notifications.该应用程序有一个设置视图,用户可以在其中切换通知。 If the permission is not granted I want to point the user to the iOS settings (like WhatsApp does).如果未授予权限,我想将用户指向 iOS 设置(就像 WhatsApp 一样)。

How do I check if the permissions got granted?如何检查权限是否被授予? Particularly in the case when a user grants permission but then decides to disable them from the iOS settings, not inside the app.特别是在用户授予权限但随后决定从 iOS 设置中禁用它们的情况下,而不是在应用程序内部。

There is a wildly popular permissions plugin which sadly does not support this particular permission.有一个广受欢迎的权限插件,遗憾的是不支持此特定权限。

You can use DependencyService to check if notifications is enabled for the app.您可以使用 DependencyService 检查应用程序是否启用了通知。

In iOS:在 iOS 中:

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

In Forms:在 Forms 中:

public interface IDeviceService
{
   bool GetApplicationNotificationSettings();
}

And after these, you can call your DependencyService from your page or view model like this:在这些之后,您可以从您的页面调用您的 DependencyService 或查看 model ,如下所示:

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

Basically you need to request authorization on each app run.基本上,您需要在每个应用程序运行时请求授权。 Therefore you'll know the authorization status and navigate users to ios settings of your app if you need to do so.因此,如果需要,您将了解授权状态并将用户导航到应用程序的 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
            });

If the permission is given this method will return true on each run.. If it changes it will return false.如果授予权限,此方法将在每次运行时返回 true。如果它发生更改,它将返回 false。

try this:尝试这个:

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

or you can do it like this (for android and iOS): https://dotnetco.de/open-app-settings-in-xamarin-forms/或者你可以这样做(对于 android 和 iOS): https://dotnetco.de/open-app-settings-in-xamarin-forms/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM