Implementing Deep Links in Xamarin.Forms and .NET MAUI

 

Implementing Deep Links in Xamarin.Forms and .NET MAUI

Introduction

Deep linking in mobile applications is an essential feature that allows users to navigate to specific pages or resources within an app directly from a URL. This functionality enhances user experience by providing a seamless way to access app content, bypassing the need for manual navigation. In this blog post, we will explore how to implement deep links in both Xamarin.Forms and .NET MAUI applications. We will provide detailed explanations and code examples to ensure a comprehensive understanding.

Setting Up Deep Links 

HTML File for Deep Link Check

First, create an HTML file to check if the app is installed and navigate accordingly:

<!DOCTYPE html>
<html>
<head>
    <title>Check App Installation</title>
</head>
<body>
    <button id="checkApp">Check if App is Installed</button>
    <script>
        document.getElementById('checkApp').addEventListener('click', function() {
            var pageName = 'Bill'; // Replace with the actual page name you want to pass

            function isAndroid() {
                return /Android/i.test(navigator.userAgent);
            }

            function isIOS() {
                return /iPhone|iPad|iPod/i.test(navigator.userAgent);
            }

            if (isAndroid()) {
                var appPackageName = 'com.packagename.app';
                var appLink = 'intent://host/Bill/#Intent;scheme=http;package=' + appPackageName + ';end';

                window.location = appLink;

                setTimeout(function() {
                    alert('App is not installed.');
                    window.location.href = 'https://play.google.com/store/apps/details?id=' + appPackageName;
                }, 2000);
            } else if (isIOS()) {
                var appLink = 'scheme://host/Bill';

                window.location = appLink;

                setTimeout(function() {
                    alert('App is not installed.');
                    window.location.href = 'https://apps.apple.com/in/app/appname/idapp';
                }, 2000);
            } else {
                alert('Unsupported device.');
            }
        });
    </script>
</body>
</html>


  • HTML Structure: Contains a button labeled "Check if App is Installed".
  • JavaScript: Adds a click event listener to the button to handle device-specific deep linking logic.
  • Device Detection: Determines if the device is Android or iOS.
  • Android: Constructs an intent-based deep link and falls back to the Play Store if the app is not installed.
  • iOS: Constructs a URL scheme-based deep link and falls back to the App Store if the app is not installed.
  • Unsupported Devices: Displays an alert if the device is neither Android nor iOS.
Android Project Configuration

In your Android project, modify the MainActivity.cs file to include the intent filters that handle deep links:
[IntentFilter(new[] { Android.Content.Intent.ActionView },
              DataScheme = "http",
              DataHost = "host",
              DataPathPrefix = "/",
              AutoVerify = true,
              Categories = new[] { Android.Content.Intent.ActionView, Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable })]

[IntentFilter(new[] { Android.Content.Intent.ActionView },
              DataScheme = "https",
              DataHost = "host",
              DataPathPrefix = "/",
              AutoVerify = true,
              Categories = new[] { Android.Content.Intent.ActionView, Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable })]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    // existing code...
}


In AndroidManifest.xml

  <activity android:name="MainActivity" android:exported="true" />
  

These intent filters ensure that URLs with the specified scheme and host are handled by your app.

iOS Project Configuration
In the info.plist file of your iOS project, add the following configuration to register your URL schemes:
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>com.companyname.app</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>host</string>
        </array>
    </dict>
</array>

Modify the AppDelegate.cs to handle incoming URLs:
public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
{
    Xamarin.Forms.Application.Current.SendOnAppLinkRequestReceived(new Uri(url.AbsoluteString));
    return true;
}

Main Project Configuration
In your shared project, modify the App.xaml.cs to handle the deep links:
protected override void OnAppLinkRequestReceived(Uri uri)
{
    base.OnAppLinkRequestReceived(uri);

    if (uri.Host.ToLower() == "host" && uri.Segments != null && uri.Segments.Length == 2)
    {
        string action = uri.Segments[1].Replace("/", "");
        bool isActionParamsValid = long.TryParse(uri.Segments[1], out long productId);
       
        // if (action.ToLower() == "pagename")
        // {
        // }
    }
}


This method extracts the page name from the URL and sets relevant flags to indicate that the navigation originated from a deep link.

Conclusion
Implementing deep links in Xamarin.Forms and .NET MAUI involves configuring both the Android and iOS projects to handle URL schemes and intent filters. By following the steps outlined in this blog post, you can enable deep linking in your applications, providing users with a seamless and direct way to access specific content within your app. Deep linking enhances user experience and engagement, making it a valuable feature for modern mobile applications.

Comments

Popular posts from this blog

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

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

School UI Design using xamarin form