In this article, I'm going to show you how to validate if the user enabled or disabled the app notifications in .NET MAUI for Android and iOS.
Create a static class NotificationsHelper
public static bool AreDeviceNotificationsEnabled()
{
#if ANDROID
return AndroidX.Core.App.NotificationManagerCompat.From(Platform.CurrentActivity).AreNotificationsEnabled();
#elif IOS
var settings = UIKit.UIApplication.SharedApplication.CurrentUserNotificationSettings.Types;
return settings != UIKit.UIUserNotificationType.None;
#endif
}
Validate
It is a good practice to help the users by asking them if they want to open the app settings, so they can enable the notifications.
if (!AreDeviceNotificationsEnabled())
{
if (showAlert)
{
var result = await Application.Current.MainPage.DisplayAlert("Enable Notifications", "Your notifications system are currently turned off", "Go to Settings", "Cancel");
if (result)
{
AppInfo.ShowSettingsUI();
}
}
}
Conclusion
In .NET MAUI it is really cool how easy you can implement a static method that allows to execute code based on each platform. Of course if you prefer to avoid the declarative conditionals you can always use the .ios.cs and .android.cs file class naming convention.
Thanks for reading! Follow me on Twitter @ivictorhugo
Top comments (0)