Xamarin.Forms – iOS/iPhone – Detecting if user said no to push/remote notifications

I assume if you’re reading this, you’re familiar with dependency injection in Xamarin Forms. What you’d create in your portable project (Your Xamarin Forms application) is the following

Xamarin.Forms custom class

public interface INotificationsInterface
{
    bool registeredForNotifications();
}

In your Xamarin.iOS project,  implement the interface with the following:

public class NotificationsInterface: INotificationsInterface
{
	public bool registeredForNotifications()
	{
		UIUserNotificationType types = UIApplication.SharedApplication.CurrentUserNotificationSettings.Types;
		if (types.HasFlag(UIUserNotificationType.Alert))
		{
			return true;
		}
		return false;
	}
}

In your main activity for your Xamarin.Forms application, perform the check as follows:

if (DependencyService.Get().registeredForNotifications())
{
	Debug.WriteLine("alerts enabled!");
} else
{
	String warningAboutAlerts ="The point of this applications is instant alerts" +
" but you choose not to receive alerts. You will need to manually check the notifications" +
	   "page or go into your iPhone's system settings to reenable alerts";
	Debug.WriteLine("No alerts allowed!");
	mainLayout.Children.Add(new Label
	{
		Text = warningAboutAlerts,
		TextColor = Color.Red,
		FontSize = 14
	});
	
}

Fairly simple stuff! For my code above, replace mainlayout with whatever you want… a dialogue box, disabling/enabling menu items… it’s entirely up to yourself!

 

 

2 comments for “Xamarin.Forms – iOS/iPhone – Detecting if user said no to push/remote notifications

  1. Ich
    April 27, 2018 at 11:31 am

    For me it says:
    Error CS0411: The type arguments for method ‘DependencyService.Get(DependencyFetchTarget)’ cannot be inferred from the usage. Try specifying the type arguments explicitly. (CS0411)

    • Evan Parsons
      May 1, 2018 at 9:10 am

      Hard for me to tell without fully knowing your setup. This code is currently being used in production, so I am pretty confident it works.

Leave a Reply to Ich Cancel reply

Your email address will not be published. Required fields are marked *