Push Notification using Firebase in xamarin form (Android and IOS)
Please, support my blog by clicking on our sponsors ad!
After Creating Project add app for both IOS and Android 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
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
Add nugget "Plugin.FirebasePushNotification" to your solutions:
Then add nugget "Xamarin.GooglePlayServices.Base" in your android project
Add "google-services.json" file in your android project.
Update BuildAction Property of file to "GoogleServicesJson". If "GoogleServicesJson" is not available then restart the solution or reload your project.
Add "GoogleService-Info.plist" file to your IOS Project and
Update BuildAction property to "BundleResource"
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
Enter Title for Notification Title
Enter Text for Notification
Click on Send test message button
Go to Target Section
Select the app you want to send and click next button
Go to Scheduling Section: select from the option and then click next button and then click on review button
Thanks for sharing the valuable content .
ReplyDeleteFirebaseInstanceId: Token retrieval failed: SERVICE_NOT_AVAILABLE Could you please help on this