Search This Blog

Monday 2 May 2022

Xamarin ios Handle Push Notification in foreground

 UserNotificationCenterDelegate.cs

using System;
using UserNotifications;
 
namespace TGS_Event_App.iOS
{
    public class UserNotificaitonCenterDelegate : UNUserNotificationCenterDelegate
    {
        public UserNotificaitonCenterDelegate()
        {
        }
 
        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
        {
            // Do something with the notification
            Console.WriteLine("Active Notification: {0}", notification);
 
            // Tell system to display the notification anyway or use
            // `None` to say we have handled the display locally.
            completionHandler(UNNotificationPresentationOptions.Alert);
        }
    }
}
 


AppDelegate.cs

if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
    // iOS 10 or later
    var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
    UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
    {
        Console.WriteLine(granted);
    });
    // For iOS 10 display notification (sent via APNS)
    UNUserNotificationCenter.Current.Delegate = new UserNotificaitonCenterDelegate();
    // For iOS 10 data message (sent via FCM)
    Messaging.SharedInstance.AutoInitEnabled = true;
    Messaging.SharedInstance.Delegate = this;
}
else
{
    // iOS 9 or before
    var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
    var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
    UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();




1 comment:

Popular Posts