【问题标题】:Check if notification permission got granted (Xamarin, iOS)检查是否授予通知权限(Xamarin,iOS)
【发布时间】:2020-03-13 20:45:56
【问题描述】:

提示用户拒绝/授予通知权限:

screenshot

该应用有一个设置视图,用户可以在其中切换通知。如果未授予权限,我想将用户指向 iOS 设置(就像 WhatsApp 一样)。

如何检查权限是否被授予?特别是在用户授予权限但随后决定从 iOS 设置中禁用它们的情况下,而不是在应用程序内部。

有一个广受欢迎的permissions plugin 很遗憾不支持此特定权限。

【问题讨论】:

    标签: c# ios xamarin permissions runtime


    【解决方案1】:

    您可以使用 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();
    

    【讨论】:

      【解决方案2】:

      基本上,您需要在每个应用运行时请求授权。因此,您将了解授权状态并在需要时将用户导航到您应用的 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。

      【讨论】:

        【解决方案3】:

        试试这个:

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

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

        【讨论】:

        • 这并不能直接回答问题,但确实很有帮助。
        猜你喜欢
        • 2021-02-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-14
        • 1970-01-01
        • 2015-04-20
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        相关资源
        最近更新 更多