Huu Bao Nguyen
Huu Bao Nguyen

Reputation: 1181

How to handle user clicks local notification on Xamarin iOS when the user turns off app?

My app receives notification and displays local User Notification.

local notification click_open_notification

When the user turns off this app and clicks to this local notification.

I want to handle event which opens this local notification.

I tried the link below:

Handle local notification tap Xamarin Forms iOS

But method ReceivedLocalNotification() doesn't seem to work (I tried showing an alert, but the Alert does not display.)

And I tried showing an alert in method DidReceiveRemoteNotification()

like Xamarin.iOS - Red & Green Notifications example, but I can't handle event "user clicks local notification when the application is turned off".

This is my code:

        [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
    public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, System.Action completionHandler)
    {
        // Show Alert 
        var alert = new UIAlertView()
        {
            Title = "LocalNotification",
            Message = $"Content: Method DidReceiveNotificationResponse()"
        };
        alert.AddButton("OK");
        alert.Show();

        if (response.IsDefaultAction)
        {
            Console.WriteLine("ACTION: Default");
        }
        if (response.IsDismissAction)
        {
            Console.WriteLine("ACTION: Dismiss");
        }
        else
        {
            Console.WriteLine($"ACTION: {response.ActionIdentifier}");
        }

        completionHandler();
    }

Please help me!

How to handle event "user clicks local notification when the application is turned off"? I'm testing on ios 12.4 and ios 13.0.

Upvotes: 2

Views: 1365

Answers (1)

Andres Castro
Andres Castro

Reputation: 1858

You have to check inside your AppDelegate.cs inside the FinishedLaunching override for the options being passed into the app. It will contain the push notification info.

UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();

if (options != null)
{
    if (options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
    {
        NSDictionary dic = options[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;

        // decide what to do with push info here
    }

    Console.WriteLine($"Startup: {nameof(AppDelegate.FinishedLaunching)} : {nameof(options)} {options}");
}

You might also want to look at UNUserNotificationCenterDelegate to better handle you push notifications if you are using ios 10+. https://learn.microsoft.com/en-us/xamarin/ios/platform/user-notifications/enhanced-user-notifications?tabs=macos#handling-foreground-app-notifications

Upvotes: 2

Related Questions