Search This Blog

Thursday 13 October 2022

Implement Push Notification In .NET MAUI (iOS)

Creation Of Certificates & Profiles
Certificate 
Create Development Certificate In Your Apple Developer Account.


Once Certificated Created, Download it and Install In Your Mac (Double Tap On Downloaded Profile)

Identifiers (Bundle Identifier)
Create Bundle Identifier Of Your App.

Devices : Add Your Testing Device in Devices Section.

Profiles (Provisional Profile)
Create Development / Distribution Provisional Profile
Once Profile Created, Download it and Install In Your Mac (Double Tap On Downloaded Profile)


Keys:  Add APNs Key In Keys Option. Used for Push Notification
Create APNs Key and Download It and Save this file in some safe place. As You Can Only Download it once.

Adding App To Firebase Console
Create / Open Existing Project In Firebase Console.



Now Click On Add App Option and select iOS 


Now Click On Register app Option To Register App.


Now Download GoogleService-Info.plist file.

Now Select Project Setting Option from Project Overview.


Now Select Cloud Messaging Tab & Select Your Newly Created App.

Here You Need To Add APN Auth Key That You Created From Apple Developer Portal.

Click on Upload Button To Upload APNs Auth Key.

Add Key ID : You will find Key From Apple Developer Portal Keys Options.
Now Click On Keys that you have created you will find Key ID.

Add Team ID:  You Will Find Team ID from Membership Detail Tab of Apple Developer Account.


All Setup Is Ready Now Lets Implement that In .NET MAUI Project.
 

Implementing Push Notification In .NET MAUI Project

Create A New .NET MAUI Project With Sample Bundle Identifier that You had created 
In Apple Developer Account.

Or You Can Edit Existing Project Bunder Identifier (App Identifier)


Now Right Click On Your Project Dependencies/net7.0-ios or net 6.0-ios Option & Click On Manage NuGet Packages.



Now Install Xamarin.Firebase.iOS.CloudMessaging Plugin.


Now Add Following Code in Your AppDelegate.cs File of iOS Platform.

AppDelegate.cs
using Firebase.CloudMessaging;
using Firebase.Core;
using Foundation;
using PushNotificationDemoMAUI.Platforms.iOS;
using UIKit;
using UserNotifications;
 
namespace PushNotificationDemoMAUI;
 
[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate, IUNUserNotificationCenterDelegate, IMessagingDelegate
{
    public object completionhandler { get; private set; }
 
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
 
    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
 
        Firebase.Core.App.Configure(new Options("AddgoogleAppID","AddgcmSenderID")
        {
            ApiKey = "AddAPIKey",
            ClientId = "ClientID",
            BundleId = "com.companyname.pushnotificationdemomaui",
            ProjectId = "Your ProjectID"
        });
 
        //Adding GoogleService-Info.plist file and calling Firebase.Core.App.Configure() is not working
        // In .NET MAUI due to that I Manually Pass all Above Info.
        // Firebase.Core.App.Configure();
 
 
        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);
            });
 
            // This Delete I used To Display Always Notification Even App Is Open
            UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate();
 
            Messaging.SharedInstance.AutoInitEnabled = true;
            Messaging.SharedInstance.Delegate = this;
        }
        UIApplication.SharedApplication.RegisterForRemoteNotifications();
 
 
        return base.FinishedLaunching(application, launchOptions);
    }
 
    [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
    public  void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
    {
        // Here Handle Notification Navigation WhenNotification Is REceived
    }
 
 
    [Export("messaging:didReceiveRegistrationToken:")]
    public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
    {
        if (Preferences.ContainsKey("DeviceToken"))
        {
            Preferences.Remove("DeviceToken");
        }
        Preferences.Set("DeviceToken", fcmToken);
 
        App.Current.MainPage.DisplayAlert("Ok",fcmToken,"OK");
    }
}
 
GoogleAppID :  You Will Get From Project Setting / General Tab (Firebase Console)

GcmSenderID: You Will Get From the GoogleService-Info.plist File
ApiKey: You Will Get From the GoogleService-Info.plist File
Client ID :  You Will Get From the GoogleService-Info.plist File
BundleID : Your Project App Identifier
ProjectID:  You will get from the Project Setting / General Tab (Firebase Console)



UserNotificationCenterDelegate.cs
using UserNotifications;
 
namespace PushNotificationDemoMAUI.Platforms.iOS
{
    public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
    {
        public UserNotificationCenterDelegate()
        {
        }
 
        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification,Action<UNNotificationPresentationOptions> completionHandler)
        {
            base.WillPresentNotification(center, notification, completionHandler);
 
            completionHandler(UNNotificationPresentationOptions.Alert);
        }
    }
}
 

Now Create  Entitlements.plist In Your Project Platforms/iOS 

In Entitlements.plist file Add aps-environment  as a key & development as a value.

Entitlements.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>aps-environment</key>
	<string>development</string>
</dict>
</plist>
 

Now All Setup Is Ready You can send push notification to device token.


Send Test Notification From Firebase Console.

Create New Campaign In Firebase Console.


Add Title & Message Then Click On Send test Message Button.


Now Add FCM Registration Token that is generated on First App Launch and Then Click on Test Button to send notification.














Saturday 24 September 2022

Monday 19 September 2022

Plugin.Maui.Popup

How to use Plugin.Maui.Popup 

Install Plugin.Maui.Popup Plugin in your project.

https://www.nuget.org/packages/Plugin.Maui.Popup   (1.0.4)








Now add xmlns:mauiPopup="clr-namespace:MauiPopup.Views;assembly=MauiPopup" this namespace in your content page.

Also replace ContentPage tag to <mauiPopup:BasePopupPage.

PopupPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<mauiPopup:BasePopupPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:mauiPopup="clr-namespace:MauiPopup.Views;assembly=MauiPopup"
             x:Class="MauiPopupDemo.PopupPage"
             Title="PopupPage">
    <VerticalStackLayout>
        <Label 
            Text="Welcome to .NET MAUI!"
            VerticalOptions="Center" 
            HorizontalOptions="Center" />
    </VerticalStackLayout>
</mauiPopup:BasePopupPage>
PopupPage.xaml.cs
using MauiPopup.Views;
namespace MauiPopupDemo;
public partial class PopupPage : BasePopupPage
{
	public PopupPage()
	{
		InitializeComponent();
	}
}


How to display Popup
MauiPopup.PopupAction.DisplayPopup(new PopupPage());
How to close Popup
MauiPopup.PopupAction.ClosePopup();

Display Popup that returning string value
string result = await MauiPopup.PopupAction.DisplayPopup(new PopupPage());
Now Pass String Value on ClosePopup Method
PopupAction.ClosePopup("hi");

Display Popup that returning other then string value
bool result = await MauiPopup.PopupAction.DisplayPopup<boo>(new PopupPage());
Now Pass Bool Value on ClosePopup Method
PopupAction.ClosePopup(true);


How to get value on popup close.

Pass Any Type of value in this method.
PopupAction.ClosePopup("hi");
To Get String Value
string result = await MauiPopup.PopupAction.DisplayPopup(new PopupPage());
To Get Other Type of Value
string result = await MauiPopup.PopupAction.DisplayPopup<int>(new PopupPage());
string result = await MauiPopup.PopupAction.DisplayPopup<bool>(new PopupPage());
string result = await MauiPopup.PopupAction.DisplayPopup<AnyTypeOfClass>(new PopupPage());

Implementation Video





Friday 2 September 2022

Create Button Control With Progress Bar (Activity Indicator) In .NET MAUI / Xamarin

This video about creating Button Control With Progress Bar (Activity Indicator) In .NET MAUI / Xamarin. 
Disable Button On Click Until Activity Indicator IsRunning Property Set to False.

GitHub URL : https://github.com/mistrypragnesh40/ButtonControlWithProgressbar


Sunday 29 May 2022

Setting Application Theme Manually In .Net MAUI

 Write Following code on App.xaml.cs

namespace CustomRenderer;
 
public partial class App : Application
{
	public App()
	{
		InitializeComponent();
                Application.Current.UserAppTheme = AppTheme.Light;
                MainPage = new AppShell();
	}
}
 

Thursday 26 May 2022

How To Access Android Context In Xamarin Forms

Write the Following Code In the Android Class of the Android Project.

var context = Android.App.Application.Context;

How to Integrate Firebase Crashlytics and Firebase Analytic In Your Xamarin Project

Firebase Crashlytics And Analytic Configuration For Android


Add Application in Google Firebase Console.
Create New Project in Google Firebase Console. Then Select Project Overview Option.

Click on +Add App Option & Select Android Project.

Add your Android Project Package Name here and then click on Register App.
Note: You will get the package name from the AndroidManifest.xml file.


Google-Service.json download this JSON file.
























Now Add this JSON file to your Android Project.















Now Right-click on the google-service.json file and Select Properties Option.















Select BuildAction : GoogleServiceJson
Copy to Output Directory: Do not copy.

Note: If you are not able to see GoogleServiceJson Build Action, Then Install the Following Plugin in your Android Project.
Xamarin.GooglePlayServices.Base
Xamarin.Google.Dagger

Xamarin.Anroid
Install the Following Plugin in your Xamarin Android Project.

Xamarin.Firebase.Analytics









Xamarin.Firebase.Crashlytics












Now Create a strings.xml file into the Resources/values folder of your Xamarin Android Project.

Add the following code in the strings.xml file
<?xml version="1.0" encoding="utf-8" ?>
<resources>
	<string name="com.google.firebase.crashlytics.mapping_file_id">none</string>
</resources>
 

Add this line in the OnCreate method of the MainActivity.cs file to send an unsent report of errors.
    Firebase.Crashlytics.FirebaseCrashlytics.Instance.SendUnsentReports();




All setup for android is done.


Firebase Crashlytics And Analytic Configuration For iOS

Create New Project in Google Firebase Console.
Then Select Project Overview Option.


Click on +Add App Option & Select iOS Project.





































Add your iOS Project Bundle Identifier here and then click on Register App.
You will get the Bundle Identifier from the Info.plist file.

Download GoogleService-Info.plist file and add this file to your Xamarin iOS Project.


Now Add this GoogleService-Info.plist file to your ios Project.



Select BuildAction: BundleResource
Copy to Output Directory: Do not copy.


Xamarin.iOS
Install the Following Plugin in your Xamarin iOS Project.

Xamarin.Firebase.iOS.Analytics










Xamarin.Firebase.iOS.Crashlytics











Now Initialize Firebase Services on AppDelegate.cs file

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
      global::Xamarin.Forms.Forms.Init();
      LoadApplication(new App());
 
      Firebase.Core.App.Configure();
      return base.FinishedLaunching(app, options);
}

All set up for iOS is done.

Now, You Can see Analytic Details & Crashes Detail on Firebase Console/Analytic, Firebase Console/Crashlytics Option.












Popular Posts