检查是否已授予通知权限(Xamarin,iOS)
Check if notification permission got granted (Xamarin, iOS)
提示用户deny/grant通知权限:
screenshot
该应用有一个设置视图,用户可以在其中切换通知。如果未授予权限,我想将用户指向 iOS 设置(就像 WhatsApp 一样)。
如何检查是否已授予权限?特别是在用户授予权限但随后决定从 iOS 设置禁用它们的情况下,而不是在应用程序内部。
有一个广受欢迎的 permissions plugin 遗憾的是不支持此特定权限。
试试这个:
Device.OpenUri(new Uri("app-settings:"));
或者您可以这样做(对于 android 和 iOS):
https://dotnetco.de/open-app-settings-in-xamarin-forms/
基本上您需要在每个应用程序上请求授权运行。因此,您将了解授权状态,并在需要时将用户导航至您应用的 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
});
如果获得许可,此方法将在每个 运行 上 return 为真。如果它发生变化,它将 return 为假。
您可以使用 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();
提示用户deny/grant通知权限:
screenshot
该应用有一个设置视图,用户可以在其中切换通知。如果未授予权限,我想将用户指向 iOS 设置(就像 WhatsApp 一样)。
如何检查是否已授予权限?特别是在用户授予权限但随后决定从 iOS 设置禁用它们的情况下,而不是在应用程序内部。
有一个广受欢迎的 permissions plugin 遗憾的是不支持此特定权限。
试试这个:
Device.OpenUri(new Uri("app-settings:"));
或者您可以这样做(对于 android 和 iOS): https://dotnetco.de/open-app-settings-in-xamarin-forms/
基本上您需要在每个应用程序上请求授权运行。因此,您将了解授权状态,并在需要时将用户导航至您应用的 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
});
如果获得许可,此方法将在每个 运行 上 return 为真。如果它发生变化,它将 return 为假。
您可以使用 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();