Push Notification using Firebase in xamarin form (Android and IOS)

Push Notification using Firebase in xamarin form (Android and IOS)
Push Notification using Firebase in xamarin form (Android and IOS)

Please, support my blog by clicking on our sponsors ad!


Watch video to understand the code:https://youtu.be/1Ixc_B86mDk

Follow steps to create push notification in both project.


Create Project for push notification

After Creating Project add app for both IOS and Android Project.

Push Notification using Firebase in xamarin form (Android and IOS)
Create app in project

For Both IOS and Android project add Package name. Package name should be same as your package name in Xamarin Android and IOS Project.

Click on Register App

Push Notification using Firebase in xamarin form (Android and IOS)
Download Google Service json.

If you are in android app then download google-services.json else if you are in ios app then download "GoogleService-Info.plist" file

Click Next then click Next then Click Continue to console button.

We have created project in firebase console now we will continue coding in xamarin.

In Android Project add Internet Permission.

Right click on android project -> Click on property -> In left menu select "Android Menifest" Select Internet from Required Permission section

Push Notification using Firebase in xamarin form (Android and IOS)
Add internet Permission in android project

Add nugget "Plugin.FirebasePushNotification" to your solutions:

Push Notification using Firebase in xamarin form (Android and IOS)
Add Plugin.FirebasePushNotification nugget to your solution

Then add nugget "Xamarin.GooglePlayServices.Base" in your android project

Push Notification using Firebase in xamarin form (Android and IOS)
Add "Xamarin.GooglePlayServices.Base" nugget in android project

Add "google-services.json" file in your android project.

Push Notification using Firebase in xamarin form (Android and IOS)
"google-services.json" file in android project.

Update BuildAction Property of file to "GoogleServicesJson". If "GoogleServicesJson" is not available then restart the solution or reload your project.

Push Notification using Firebase in xamarin form (Android and IOS)
Update Build Action

Add "GoogleService-Info.plist" file to your IOS Project and 

Push Notification using Firebase in xamarin form (Android and IOS)
"GoogleService-Info.plist" file to IOS Project

Update BuildAction property to "BundleResource"

Update BuildAction property to "BundleResource"

Add following code in your android project.

Add new Class Named as "MainApplication" in android project paste following code:

    [Application]
    public class MainApplication : Application
    {
        public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();

            //Set the default notification channel for your app when running Android Oreo
            if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                //Change for your default notification channel id here
                FirebasePushNotificationManager.DefaultNotificationChannelId = "FirebasePushNotificationChannel";

                //Change for your default notification channel name here
                FirebasePushNotificationManager.DefaultNotificationChannelName = "General";
            }


            //If debug you should reset the token each time.
            #if DEBUG
                        FirebasePushNotificationManager.Initialize(this, true);
            #else
                                      FirebasePushNotificationManager.Initialize(this,false);
            #endif

            //Handle notification when app is closed here
            CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
            {


            };


        }
    }  

Add Following code in MainActivity class of your android project in oncreate method.

       private bool IsNotification = false;
        private IDictionary<string, object> NotificationData;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            if (!IsNotification)
                LoadApplication(new App());
            FirebasePushNotificationManager.ProcessIntent(this, Intent);

            CrossFirebasePushNotification.Current.OnNotificationOpened += (s, p) =>
            {
                System.Diagnostics.Debug.WriteLine("NOTIFICATION Opened", p.Data);
                NotificationData = p.Data;
                IsNotification = true;
                LoadApplication(new App(IsNotification, NotificationData));
            };


        }  

Add Following code in IOS Project

In Info.plist  add following line

  <key>FirebaseAppDelegateProxyEnabled</key>
  <false/>

In AppDelegate file: Add following code in FinishedLaunching:

 public override bool FinishedLaunching(UIApplication app, NSDictionary options)
 {
       global::Xamarin.Forms.Forms.Init();
       LoadApplication(new App());

       FirebasePushNotificationManager.Initialize(options, true);
       return base.FinishedLaunching(app, options);
 }  

Add following method in Appdelegate file

        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            FirebasePushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
        }

        public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
        {
            FirebasePushNotificationManager.RemoteNotificationRegistrationFailed(error);

        }
        // To receive notifications in foregroung on iOS 9 and below.
        // To receive notifications in background in any iOS version
        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {
            // If you are receiving a notification message while your app is in the background,
            // this callback will not be fired 'till the user taps on the notification launching the application.

            // If you disable method swizzling, you'll need to call this method. 
            // This lets FCM track message delivery and analytics, which is performed
            // automatically with method swizzling enabled.
            FirebasePushNotificationManager.DidReceiveMessage(userInfo);
            // Do your magic to handle the notification data
            System.Console.WriteLine(userInfo);

            completionHandler(UIBackgroundFetchResult.NewData);
        }  

In Your Main Project, In App.xaml.cs add following code in App() Construction:

         public static string Data { get; set; }
        public App(bool hasNotification = false, IDictionary<string, object> notificationData = null)
        {
            InitializeComponent();

            if (!hasNotification)
                MainPage = new AppShell();
            else
            {
                foreach (var data in notificationData)
                {
                    if (data.Key == "LoginPage")
                    {
                        MainPage = new LoginPage();
                        return;
                    }
                }
            }          
            CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
            {
                System.Diagnostics.Debug.WriteLine($"TOKEN : {p.Token}");
            };
            CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
            {

                System.Diagnostics.Debug.WriteLine("Received");
                foreach (var data in p.Data)
                {
                    System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                }

            };
            CrossFirebasePushNotification.Current.OnNotificationOpened += (s, p) =>
            {
                System.Diagnostics.Debug.WriteLine("Opened");
                foreach (var data in p.Data)
                {
                    System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                }


            };  

Now we will test from firebase console.

From above code you will get Token from p.Token. copy that token

Go to firebase console -> go to cloud messaging -> Click on New Campaign or Click on Sent first message.

In Notification Section

Push Notification using Firebase in xamarin form (Android and IOS)
Setup Notification

Enter Title for Notification Title

Enter Text for Notification

Click on Send test message button

Push Notification using Firebase in xamarin form (Android and IOS)


Paste Token in textbox and click on round + button
then click on test button.

Go to Target Section

Select the app you want to send and click next button

Push Notification using Firebase in xamarin form (Android and IOS)
Target your app

Go to Scheduling Section: select from the option and then click next button and then click on review button

Push Notification using Firebase in xamarin form (Android and IOS)
Schedule push notification

Add Additional options (optional)


Push Notification using Firebase in xamarin form (Android and IOS)
Schedule Notification

Review message dialog will open Click on Publish button.

Push Notification using Firebase in xamarin form (Android and IOS)
Publish notification

You will get notification. first notification may take up to 5 minutes. 

Hope it is helpful to you. enjoy coding and please share your feedback.

Comments

  1. Thanks for sharing the valuable content .
    FirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE Could you please help on this

    ReplyDelete

Post a Comment

Popular posts from this blog

Explore the UI libraries available for .NET MAUI at no cost.

School UI Design using xamarin form