Aller au contenu
Ingénierie · · 6 min de lecture

.NET MAUI Deep Linking : guide d'implémentation

Par L'équipe Tolinku
|
Deep linking avec .NET MAUI : guide d'implémentation

.NET MAUI (Multi-platform App UI) succède à Xamarin.Forms. Il utilise une seule base de code C# pour iOS, Android, macOS et Windows, le code propre à chaque plateforme étant isolé dans le Platforms/ répertoire. Le deep linking dans MAUI suit les mêmes schémas natifs (Universal Links sur iOS, App Links sur Android), mais s'intègre à la navigation Shell de MAUI et à l'injection de dépendances.

Pour Xamarin.Forms (ancien), voir Xamarin deep linking : configuration multiplateforme. Pour la vue d'ensemble multiplateforme, voir guide du deep linking multiplateforme pour 2026.

Configuration iOS

1. Entitlement Associated Domains

Créez ou mettez à jour Platforms/iOS/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>com.apple.developer.associated-domains</key>
    <array>
        <string>applinks:yourdomain.com</string>
    </array>
</dict>
</plist>

Référencez-le dans votre .csproj:

<PropertyGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">
    <CodesignEntitlements>Platforms/iOS/Entitlements.plist</CodesignEntitlements>
</PropertyGroup>

2. Fichier AASA

Hébergez-le à https://yourdomain.com/.well-known/apple-app-site-association:

{
  "applinks": {
    "details": [{
      "appIDs": ["TEAMID.com.yourcompany.yourapp"],
      "components": [
        { "/": "/products/*" },
        { "/": "/offers/*" },
        { "/": "/referral/*" }
      ]
    }]
  }
}

Récupérez votre Team ID depuis le compte Apple Developer, sous Membership Details.

Dans Platforms/iOS/AppDelegate.cs:

using Foundation;
using UIKit;

[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();

    [Export("application:continueUserActivity:restorationHandler:")]
    public bool ContinueUserActivity(
        UIApplication application,
        NSUserActivity userActivity,
        UIApplicationRestorationHandler completionHandler)
    {
        if (userActivity.ActivityType == NSUserActivityType.BrowsingWeb
            && userActivity.WebPageUrl != null)
        {
            var url = userActivity.WebPageUrl.ToString();
            DeepLinkService.Instance.HandleUrl(url);
            return true;
        }
        return false;
    }
}

Configuration Android

1. Intent Filters

Dans Platforms/Android/AndroidManifest.xml:

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

    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https"
              android:host="yourdomain.com"
              android:pathPrefix="/products" />
        <data android:scheme="https"
              android:host="yourdomain.com"
              android:pathPrefix="/offers" />
        <data android:scheme="https"
              android:host="yourdomain.com"
              android:pathPrefix="/referral" />
    </intent-filter>
</activity>

Ou utilisez le IntentFilter attribut sur MainActivity.cs:

using Android.App;
using Android.Content;
using Android.Content.PM;

[Activity(
    Theme = "@style/Maui.SplashTheme",
    MainLauncher = true,
    Exported = true,
    LaunchMode = LaunchMode.SingleTop)]
[IntentFilter(
    new[] { Intent.ActionView },
    Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
    DataScheme = "https",
    DataHost = "yourdomain.com",
    DataPathPrefix = "/products",
    AutoVerify = true)]
[IntentFilter(
    new[] { Intent.ActionView },
    Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
    DataScheme = "https",
    DataHost = "yourdomain.com",
    DataPathPrefix = "/offers",
    AutoVerify = true)]
[IntentFilter(
    new[] { Intent.ActionView },
    Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
    DataScheme = "https",
    DataHost = "yourdomain.com",
    DataPathPrefix = "/referral",
    AutoVerify = true)]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        HandleIntent(Intent);
    }

    protected override void OnNewIntent(Intent intent)
    {
        base.OnNewIntent(intent);
        HandleIntent(intent);
    }

    private void HandleIntent(Intent intent)
    {
        if (intent?.Data != null)
        {
            DeepLinkService.Instance.HandleUrl(intent.Data.ToString());
        }
    }
}

Hébergez-le à https://yourdomain.com/.well-known/assetlinks.json:

[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "com.yourcompany.yourapp",
      "sha256_cert_fingerprints": [
        "YOUR_SIGNING_KEY_FINGERPRINT"
      ]
    }
  }
]

Créez un service que les deux plateformes appellent avec l'URL reçue :

// Services/DeepLinkService.cs

public class DeepLinkService
{
    private static DeepLinkService _instance;
    public static DeepLinkService Instance => _instance ??= new DeepLinkService();

    private string _pendingUrl;
    private bool _isReady;

    public void HandleUrl(string urlString)
    {
        if (_isReady)
        {
            RouteUrl(urlString);
        }
        else
        {
            // L'app n'est pas encore entièrement initialisée, mise en file d'attente de l'URL
            _pendingUrl = urlString;
        }
    }

    public void MarkReady()
    {
        _isReady = true;
        if (!string.IsNullOrEmpty(_pendingUrl))
        {
            RouteUrl(_pendingUrl);
            _pendingUrl = null;
        }
    }

    private void RouteUrl(string urlString)
    {
        if (!Uri.TryCreate(urlString, UriKind.Absolute, out var uri))
            return;

        var path = uri.AbsolutePath.TrimEnd('/');
        var query = System.Web.HttpUtility.ParseQueryString(uri.Query);

        MainThread.BeginInvokeOnMainThread(async () =>
        {
            await NavigateFromDeepLink(path, query);
        });
    }

    private async Task NavigateFromDeepLink(
        string path,
        System.Collections.Specialized.NameValueCollection query)
    {
        // Page produit
        var productMatch = System.Text.RegularExpressions.Regex.Match(
            path, @"^/products/([^/]+)$");
        if (productMatch.Success)
        {
            var productId = productMatch.Groups[1].Value;
            await Shell.Current.GoToAsync(
                $"//products/detail?productId={productId}");
            return;
        }

        // Page offre
        var offerMatch = System.Text.RegularExpressions.Regex.Match(
            path, @"^/offers/([^/]+)$");
        if (offerMatch.Success)
        {
            var offerId = offerMatch.Groups[1].Value;
            await Shell.Current.GoToAsync(
                $"//offers/detail?offerId={offerId}");
            return;
        }

        // Parrainage
        var referralMatch = System.Text.RegularExpressions.Regex.Match(
            path, @"^/referral/([^/]+)$");
        if (referralMatch.Success)
        {
            var referrerId = referralMatch.Groups[1].Value;
            // Enregistre le parrainage, puis redirige vers l'accueil
            Preferences.Set("referrer_id", referrerId);
            await Shell.Current.GoToAsync("//home");
            return;
        }

        // Par défaut
        await Shell.Current.GoToAsync("//home");
    }
}

Configuration de la navigation Shell

Enregistrez les routes dans AppShell.xaml.cs:

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();

        // Enregistre les routes de détail pour le deep linking
        Routing.RegisterRoute("products/detail", typeof(ProductDetailPage));
        Routing.RegisterRoute("offers/detail", typeof(OfferDetailPage));
        Routing.RegisterRoute("referral", typeof(ReferralPage));
    }
}

AppShell.xaml

<?xml version="1.0" encoding="UTF-8" ?>
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:pages="clr-namespace:YourApp.Pages"
       x:Class="YourApp.AppShell">

    <TabBar>
        <ShellContent Title="Home"
                      Route="home"
                      ContentTemplate="{DataTemplate pages:HomePage}" />
        <ShellContent Title="Products"
                      Route="products"
                      ContentTemplate="{DataTemplate pages:ProductsPage}" />
        <ShellContent Title="Offers"
                      Route="offers"
                      ContentTemplate="{DataTemplate pages:OffersPage}" />
    </TabBar>
</Shell>

Gestion des paramètres de requête

Utilisez QueryProperty attribut pour recevoir les paramètres dans vos pages :

[QueryProperty(nameof(ProductId), "productId")]
public partial class ProductDetailPage : ContentPage
{
    private string _productId;
    public string ProductId
    {
        get => _productId;
        set
        {
            _productId = value;
            LoadProduct(value);
        }
    }

    private async void LoadProduct(string productId)
    {
        if (string.IsNullOrEmpty(productId)) return;

        try
        {
            var product = await ProductService.GetByIdAsync(productId);
            BindingContext = product;
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", "Could not load product", "OK");
            await Shell.Current.GoToAsync("..");
        }
    }
}

Initialisation de l'app

Signalez que l'app est prête une fois entièrement initialisée :

// App.xaml.cs
public partial class App : Application
{
    public App()
    {
        InitializeComponent();
        MainPage = new AppShell();
    }

    protected override void OnStart()
    {
        base.OnStart();
        // Signale que l'app peut traiter les deep links
        DeepLinkService.Instance.MarkReady();
    }
}

Alternative à l'injection de dépendances

Au lieu du singleton, utilisez l'injection de dépendances intégrée de MAUI :

// MauiProgram.cs
public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
        });

    // Enregistre le service de deep links
    builder.Services.AddSingleton<IDeepLinkService, DeepLinkService>();

    return builder.Build();
}
// Interface
public interface IDeepLinkService
{
    void HandleUrl(string url);
    void MarkReady();
}

Injectez-le là où vous en avez besoin :

public partial class App : Application
{
    private readonly IDeepLinkService _deepLinkService;

    public App(IDeepLinkService deepLinkService)
    {
        InitializeComponent();
        _deepLinkService = deepLinkService;
        MainPage = new AppShell();
    }

    protected override void OnStart()
    {
        base.OnStart();
        _deepLinkService.MarkReady();
    }
}

Tests

Simulateur iOS

xcrun simctl openurl booted "https://yourdomain.com/products/abc123"

Android Emulator

adb shell am start -a android.intent.action.VIEW \
  -d "https://yourdomain.com/products/abc123" \
  -c android.intent.category.BROWSABLE

Tests unitaires du routeur

[TestFixture]
public class DeepLinkServiceTests
{
    [Test]
    public void ParsesProductUrl()
    {
        var uri = new Uri("https://yourdomain.com/products/abc123");
        var path = uri.AbsolutePath;

        var match = Regex.Match(path, @"^/products/([^/]+)$");

        Assert.IsTrue(match.Success);
        Assert.AreEqual("abc123", match.Groups[1].Value);
    }

    [Test]
    public void ParsesQueryParameters()
    {
        var uri = new Uri("https://yourdomain.com/products/abc123?ref=email&campaign=summer");
        var query = System.Web.HttpUtility.ParseQueryString(uri.Query);

        Assert.AreEqual("email", query["ref"]);
        Assert.AreEqual("summer", query["campaign"]);
    }

    [Test]
    public void HandlesTrailingSlash()
    {
        var uri = new Uri("https://yourdomain.com/products/abc123/");
        var path = uri.AbsolutePath.TrimEnd('/');

        var match = Regex.Match(path, @"^/products/([^/]+)$");

        Assert.IsTrue(match.Success);
        Assert.AreEqual("abc123", match.Groups[1].Value);
    }
}

Tolinku pour les apps .NET MAUI

Tolinku héberge les fichiers de vérification AASA et assetlinks.json. Renseignez votre Team ID iOS, votre bundle identifier, votre nom de package Android et vos empreintes SHA-256 dans les paramètres de l'Appspace paramètres de votre Appspace, et Tolinku génère automatiquement les deux fichiers. Consultez le guide de configuration iOS et à guide de configuration Android pour la mise en place.

Pour l'approche Xamarin historique, voir Xamarin deep linking : configuration multiplateforme. Pour partir de zéro, voir implémenter des deep links de zéro.

Recevez nos conseils sur le deep linking par e-mail

Un e-mail par semaine. Pas de spam.

Prêt à ajouter le deep linking à votre app ?

Configurez les Universal Links, les App Links, le deep linking différé et l'analytique en quelques minutes. Gratuit pour commencer.