# Get started with Avalonia

> Build a small Avalonia app that enrols your face and verifies it offline, on your own phone.

Source: https://docs.faceping.ai/start/avalonia/

What you'll build

### A face check that works in airplane mode

An app that enrols your face, verifies it live with a head-turn liveness check, and still matches with no network.

About 10 minutes
Android or iPhone
Free sandbox key

## Get a sandbox key

Sign up at [app.faceping.ai/signup](https://app.faceping.ai/signup?platform=avalonia) with your email, then open [**Developers → Sandbox keys → Create sandbox key**](https://app.faceping.ai/developers). It starts with `fp_test_`. It also works on the API for your practice list, so keep test apps within your team, and revoke the key under Developers if it leaks.

The sandbox is free and instant: up to 25 faces per device, each deleted 24 hours after it was enrolled. No card, no approval.

## Create the project

You need the [.NET 10 SDK](https://dotnet.microsoft.com/download) with the Android and iOS workloads, and an Android phone (Android 7 or later, 64-bit) or an iPhone with a cable. The Avalonia template makes a shared project for your screens, plus one project per platform.

```bash
dotnet new install Avalonia.Templates
dotnet new avalonia.xplat -n FaceCheck
cd FaceCheck
```

First mobile .NET app on this machine?

The 10 minutes assume your machine already builds .NET apps for phones. If it doesn't, set it up first (the workloads and Android tools take a while to download):

- **.NET workloads:** `dotnet workload install android ios` (on macOS it may need `sudo`, and it takes a few minutes).
- **Android:** the Android SDK and a JDK. Install them with [Android Studio](https://developer.android.com/studio), or let .NET fetch them with `dotnet build -t:InstallAndroidDependencies` (Microsoft's [Android set-up guide](https://learn.microsoft.com/dotnet/android/getting-started/installation/dependencies) has the full command). Turn on **USB debugging** on the phone.
- **iPhone:** a Mac with [Xcode](https://developer.apple.com/xcode/) 26 or later, signed in with your Apple ID (**Xcode → Settings → Apple Accounts**).
- **Avalonia:** see Avalonia's [mobile set-up](https://docs.avaloniaui.net/docs/guides/platforms/android/setting-up-your-developer-environment-for-android).

FacePing runs on Android and iOS, so remove the desktop and browser projects (they'd still build, but face checks there report that FacePing runs on Android and iOS devices):

```bash
dotnet sln FaceCheck.slnx remove FaceCheck.Desktop/FaceCheck.Desktop.csproj FaceCheck.Browser/FaceCheck.Browser.csproj
rm -rf FaceCheck.Desktop FaceCheck.Browser
```

## Add FacePing

One package, in the shared project and in both platform projects. It brings the face models, liveness checks and a camera control with it.

```bash
dotnet add FaceCheck package FacePing.Sdk.Avalonia --prerelease
dotnet add FaceCheck.Android package FacePing.Sdk.Avalonia --prerelease
dotnet add FaceCheck.iOS package FacePing.Sdk.Avalonia --prerelease
```

FacePing for Avalonia is in preview: `--prerelease` gets the latest preview from [NuGet](https://www.nuget.org/packages/FacePing.Sdk.Avalonia). It needs Avalonia 12.

The first restore downloads about 170 MB, mostly Microsoft's ONNX Runtime (the engine the face models run on). After that it comes from your NuGet cache. Expect an Android app of about 72 MB and an iPhone app of about 80 MB; see the size note under [Run it on your phone](#run-it-on-your-phone) for a smaller Android app.

Then set the platforms FacePing runs on: 64-bit Android 7 (API 24) or later, and iOS 15.1 or later. The template's minimums are lower, and the build stops with a message until you change them. Give each app your own reverse-DNS id too (iOS signs the app with it). Each part of the id must be a plain word that isn't a Java keyword (so not `final` or `new`), or the Android build fails.

In `FaceCheck.Android.csproj`, change the template's `SupportedOSPlatformVersion` (23) and `ApplicationId` lines to these, and add `RuntimeIdentifiers` below them:

```xml title="FaceCheck.Android.csproj"
<SupportedOSPlatformVersion>24</SupportedOSPlatformVersion>
<ApplicationId>com.yourcompany.facecheck</ApplicationId>
<RuntimeIdentifiers>android-arm64;android-x64</RuntimeIdentifiers>
```

In `FaceCheck.iOS.csproj`, change `SupportedOSPlatformVersion` (13.0) and add an `ApplicationId` below it:

```xml title="FaceCheck.iOS.csproj"
<SupportedOSPlatformVersion>15.1</SupportedOSPlatformVersion>
<ApplicationId>com.yourcompany.facecheck</ApplicationId>
```

The template's iOS `Info.plist` also has its own `CFBundleIdentifier` (`companyName.FaceCheck`), which wins over `ApplicationId` without a word, and `MinimumOSVersion` 13.0, which stops the build. In `FaceCheck.iOS/Info.plist`, delete the `CFBundleIdentifier` key and its `<string>`, and change `MinimumOSVersion` to `15.1`. If you've already built for iOS, build once with `--no-incremental` so the change is picked up.

The name under the app's icon on Android comes from `MainActivity`: in `FaceCheck.Android/MainActivity.cs`, change `Label = "FaceCheck.Android"` to `Label = "FaceCheck"`.

## Allow the camera

The package adds Android's camera permission for you. iOS asks the person with your own words: add them to the iOS project's Info.plist.

```xml title="FaceCheck.iOS/Info.plist"
<!-- inside <dict> -->
<key>NSCameraUsageDescription</key>
<string>FaceCheck uses the camera to verify your face.</string>
```

On Android, keep face data out of backups. FacePing encrypts it with a key kept in the Android Keystore, which backups don't include, so a backed-up copy could never be read on another phone (and face data shouldn't leave the device anyway). Turn backup off, and add rules for Android 12 and later, which also copy data when someone moves to a new phone:

```xml title="FaceCheck.Android/Properties/AndroidManifest.xml"
<!-- add these three to <application> -->
<application android:label="FaceCheck" android:icon="@drawable/Icon" android:allowBackup="false"
             android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" />
```

```xml title="FaceCheck.Android/Resources/xml/data_extraction_rules.xml"
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
  <cloud-backup>
    <exclude domain="file" path="faceping/" />
    <exclude domain="sharedpref" path="ai.faceping.sdk.keys.xml" />
  </cloud-backup>
  <device-transfer>
    <exclude domain="file" path="faceping/" />
    <exclude domain="sharedpref" path="ai.faceping.sdk.keys.xml" />
  </device-transfer>
</data-extraction-rules>
```

```xml title="FaceCheck.Android/Resources/xml/backup_rules.xml"
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
  <exclude domain="file" path="faceping/" />
  <exclude domain="sharedpref" path="ai.faceping.sdk.keys.xml" />
</full-backup-content>
```

On iOS there's nothing to add: FacePing keeps its folder out of iCloud and computer backups itself.

## Turn FacePing on

Each platform project starts the app in `CustomizeAppBuilder`. In both, add the `using` at the top of the file and replace the template's `CustomizeAppBuilder` method with this one, which adds FacePing with your sandbox key (keep the rest of the class).

```csharp title="FaceCheck.Android/Application.cs"
using FacePing.Sdk.Avalonia;

protected override AppBuilder CustomizeAppBuilder(AppBuilder builder) =>
    base.CustomizeAppBuilder(builder)
        .WithInterFont()
        .UseFacePing(o => o.SandboxKey = "fp_test_…");
```

```csharp title="FaceCheck.iOS/AppDelegate.cs"
using FacePing.Sdk.Avalonia;

protected override AppBuilder CustomizeAppBuilder(AppBuilder builder) =>
    base.CustomizeAppBuilder(builder)
        .WithInterFont()
        .UseFacePing(o => o.SandboxKey = "fp_test_…");
```

## Add the screen

A camera control and two buttons (`Classes="accent"` makes Verify the main one): one enrols your face on the phone, the other verifies it. `FaceCameraView` is drawn by Avalonia, so it sits in your layout like any other control.

```xml title="FaceCheck/Views/MainView.axaml"
<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:fp="using:FacePing.Sdk.Avalonia"
             x:Class="FaceCheck.Views.MainView">
  <StackPanel Margin="24,48,24,24" Spacing="16">
    <fp:FaceCameraView x:Name="Camera" Height="420" />
    <TextBlock x:Name="Status" FontSize="18" HorizontalAlignment="Center" />
    <Button Content="Enrol my face" Click="OnEnroll" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Padding="14" />
    <Button Content="Verify" Click="OnVerify" Classes="accent" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Padding="14" />
  </StackPanel>
</UserControl>
```

```csharp title="FaceCheck/Views/MainView.axaml.cs"
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using FacePing.Sdk;
using FacePing.Sdk.Avalonia;

namespace FaceCheck.Views;

public partial class MainView : UserControl
{
    readonly IFacePing faceping = IFacePing.Current;

    public MainView()
    {
        InitializeComponent();
        // No camera permission, or no front camera: the message says which.
        Camera.CameraFailed += (_, message) => Status.Text = message;
    }

    protected override async void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        try
        {
            // Optional: the SDK activates your sandbox key itself on first use (the first run needs a connection).
            // Syncing here shows a key problem straight away and picks up a face enrolled earlier (kept for 24 hours).
            var sync = await faceping.SyncAsync();
            // On a check-in device: who arrived, or Revoked (token revoked, mistyped or its list deleted).
            if (!faceping.IsSandbox)
                Status.Text = $"{sync.Enrolled} people synced ({sync.Status})";
        }
        catch (Exception ex) when (ex is FacePingSetupException or FacePingModelException)
        {
            Status.Text = ex.Message;
        }
    }

    async void OnEnroll(object? sender, RoutedEventArgs e)
    {
        try
        {
            var photo = await Camera.CaptureAsync();
            var result = await faceping.EnrollAsync("me", photo);
            Status.Text = result.Outcome == EnrollOutcome.Enrolled
                ? "Enrolled. Now tap Verify."
                : $"Try again: {result.Outcome}";
        }
        catch (Exception ex) when (ex is FacePingSetupException or FacePingModelException or InvalidOperationException)
        {
            // For example a mistyped key, no connection on the very first run (the sandbox key is
            // activated once), or the camera didn't deliver a picture. The message says which.
            Status.Text = ex.Message;
        }
    }

    async void OnVerify(object? sender, RoutedEventArgs e)
    {
        try
        {
            // A live check: matches your face, then asks you to turn your head (liveness).
            var result = await faceping.VerifyLiveAsync("me", Camera);
            Status.Text = $"{result.Outcome} · {result.Elapsed.TotalSeconds:0.00} s";
        }
        catch (Exception ex) when (ex is FacePingSetupException or FacePingModelException)
        {
            Status.Text = ex.Message;
        }
    }
}
```

The template's `MainView` sets a view model as its `DataContext` in `App.axaml.cs`; it does no harm, or remove it.

## Run it on your phone

Plug your phone in and run a Release build. The first run needs a connection, to activate your sandbox key. Tap **Enrol my face**, then **Verify**: you should see `Match`. Use a phone: the iOS simulator has no front camera, and an Android emulator only has one if you map your computer's webcam to it in the emulator's camera settings, which is slower and less reliable for the liveness check.

```bash title="Android"
dotnet build FaceCheck.Android -t:Run -c Release

# Several phones connected, or installing a built app? Use adb (on macOS it's in
# ~/Library/Android/sdk/platform-tools if it isn't on your PATH):
adb devices
adb install -r FaceCheck.Android/bin/Release/net10.0-android/com.yourcompany.facecheck-Signed.apk
```

```bash title="iOS"
# Simulators have no front camera: use a connected iPhone. The easiest way is Run in Rider or
# Visual Studio. From the command line, build, then install with Xcode's tools (use your ApplicationId):
dotnet build FaceCheck.iOS -c Release -p:RuntimeIdentifier=ios-arm64
xcrun devicectl list devices
xcrun devicectl device install app --device <device id> FaceCheck.iOS/bin/Release/net10.0-ios/ios-arm64/FaceCheck.iOS.app
xcrun devicectl device process launch --device <device id> com.yourcompany.facecheck
```

**First time on an iPhone?** `dotnet build` signs the app with a provisioning profile it finds on your Mac, but it can't create one. If the build says there's no profile for your ApplicationId, make one once in Xcode: create a new iOS App project with the same bundle identifier, pick your **Team** under **Signing & Capabilities**, and run it on the phone. Then build again. A free Apple ID works too, but always needs this one-off step, and its profiles last 7 days. Allow 5 to 10 minutes for it the first time.

The iOS Release build prints two trim warnings that come from the Avalonia template, not FacePing (`IL2026` for the template's `ViewLocator` and `IL2104` for `Avalonia.DesignerSupport`): they're harmless here.

If you have more than one certificate or team, name the ones to use: add `-p:CodesignKey="Apple Development: Your Name (XXXXXXXXXX)"` and, if needed, `-p:CodesignProvision="Your profile name"` to the `dotnet build` line. `security find-identity -v -p codesigning` lists your certificates.

On the phone, turn on **Developer Mode** (**Settings → Privacy & Security → Developer Mode**) and, if iOS says the developer isn't trusted, trust it under **Settings → General → VPN & Device Management**.

The Android build includes the phone (`arm64`) and emulator (`x86_64`) versions of the face engine. For a smaller app, set `<RuntimeIdentifiers>android-arm64</RuntimeIdentifiers>` (phones only), or publish an Android App Bundle so each phone downloads only its own.

**Now switch on airplane mode and tap Verify again.** Still a match: the check ran entirely on your phone.

## You've built a face check that works offline

Next, make it real: verify the people in your app (members, visitors or people with tickets), and apply to go live when you're ready.

- [Clone the finished app](https://github.com/faceping/avalonia-starter): github.com/faceping/avalonia-starter
- [How the SDK works](https://docs.faceping.ai/sdk/): Liveness, storage, sandbox limits
- [Avalonia reference](https://docs.faceping.ai/sdk/avalonia/): Every type and method
- [Go to production](https://docs.faceping.ai/going-live/): Apply and sync faces to devices

## Try a check-in device on your practice list

This is the ticketing flow, end to end, in the sandbox: a person enrols through your server or an enrolment link, and a check-in device verifies them offline.

1. Create your practice list, if your account doesn't have one: **New list** in the [dashboard](https://app.faceping.ai/lists) asks for everything it needs, or use [quickstart steps 1 and 2](https://docs.faceping.ai/quickstart/#1-create-a-check-in-list) (create the list, then set its widget details: enrolment links need them). Then enrol someone on it with your sandbox key: open an enrolment link ([quickstart step 3](https://docs.faceping.ai/quickstart/#3-create-an-enrolment-link-for-a-person); links last 30 minutes unless you pass `validForHours`), or enrol a selfie from your server with the copy-paste request in [Enrol someone from your server](https://docs.faceping.ai/quickstart/#enrol-someone-from-your-server). Note their `personId`, for example `ACME-000123` (if your team shares the practice list, pick your own).
2. Add a check-in device: the list's **Devices** tab in the [dashboard](https://app.faceping.ai/lists), or `POST /v1/lists/{listId}/devices`. Copy the `fpd_` device token: it's shown once.
3. Check the token works before you build: `curl https://api-eu.faceping.ai/v1/device -H "X-Device-Token: fpd_…"` returns the list's name and `peopleEnrolled`. It doesn't download any faces or count as a sync.
4. Make a device build that sits next to your sandbox app: copy the solution folder, leaving out every `bin` and `obj` folder (they hold the sandbox build, which is easy to install by mistake). In the copy, give both platform projects their own `ApplicationId` (for example `com.yourcompany.facecheck.device`) and name (`Label` in `MainActivity.cs`, `CFBundleDisplayName` in `Info.plist`, for example `FaceCheck Device`).
5. In the copy, set FacePing up with the device token in both platform projects (`FaceCheck.Android/Application.cs` and `FaceCheck.iOS/AppDelegate.cs`):

```csharp title="CustomizeAppBuilder (device build, both platform projects)"
protected override AppBuilder CustomizeAppBuilder(AppBuilder builder) =>
    base.CustomizeAppBuilder(builder)
        .WithInterFont()
        .UseFacePing(o => o.DeviceToken = "fpd_…");   // in place of o.SandboxKey
```

Building the token in is fine for this test; an app you publish pairs each device at runtime instead, with `PairAsync` (see [Pair each device](https://docs.faceping.ai/devices/#pair-each-device)).

6. Replace the copy's screen with the device version. It verifies the person you enrolled, syncs when the screen opens and shows every later sync. People enrol on the server, not in the app (`EnrollAsync` throws `InvalidOperationException` on a device), so there's no enrol button:

```xml title="FaceCheck/Views/MainView.axaml (device build)"
<UserControl xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:fp="using:FacePing.Sdk.Avalonia"
             x:Class="FaceCheck.Views.MainView">
  <StackPanel Margin="24,48,24,24" Spacing="16">
    <fp:FaceCameraView x:Name="Camera" Height="420" />
    <TextBlock x:Name="Status" FontSize="18" HorizontalAlignment="Center" TextWrapping="Wrap" TextAlignment="Center" />
    <Button Content="Verify" Click="OnVerify" Classes="accent" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Padding="14" />
  </StackPanel>
</UserControl>
```

```csharp title="FaceCheck/Views/MainView.axaml.cs (device build)"
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Threading;
using FacePing.Sdk;
using FacePing.Sdk.Avalonia;

namespace FaceCheck.Views;

public partial class MainView : UserControl
{
    const string PersonId = "ACME-000123";   // the person you enrolled

    readonly IFacePing faceping = IFacePing.Current;

    public MainView()
    {
        InitializeComponent();
        Camera.CameraFailed += (_, message) => Status.Text = message;
        // Show every sync: the one this page asks for, and the ones FacePing runs every few minutes.
        faceping.Synced += (_, sync) => Dispatcher.UIThread.Post(() => ShowSync(sync));
    }

    protected override async void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
    {
        base.OnAttachedToVisualTree(e);
        try
        {
            await faceping.SyncAsync();   // its result arrives through Synced too
        }
        catch (Exception ex) when (ex is FacePingSetupException or FacePingModelException)
        {
            Status.Text = ex.Message;
        }
    }

    // Revoked: the token was revoked, mistyped or its list deleted, and the device wiped its faces.
    void ShowSync(SyncResult sync) => Status.Text = $"{sync.Enrolled} people synced ({sync.Status})";

    async void OnVerify(object? sender, RoutedEventArgs e)
    {
        try
        {
            var result = await faceping.VerifyLiveAsync(PersonId, Camera);
            Status.Text = result.Outcome switch
            {
                VerifyOutcome.Match => $"Match · {result.Elapsed.TotalSeconds:0.00} s",
                VerifyOutcome.NotEnrolled => $"{PersonId} isn't on this device yet: enrol them, then wait for the next sync.",
                _ => $"Try again: {result.Outcome}"
            };
        }
        catch (Exception ex) when (ex is FacePingSetupException or FacePingModelException)
        {
            Status.Text = ex.Message;
        }
    }
}
```

7. Run the device build as in [Run it on your phone](#run-it-on-your-phone), using the device build's `ApplicationId` in the install commands. It downloads the list's faces at start-up and every few minutes after; the status line shows how many people synced and the sync status, and updates with each sync. Then tap **Verify**, with no network if you like.

Each face stays on the device no longer than its 24 hours on the practice list. See [Devices and offline sync](https://docs.faceping.ai/devices/).

The [finished app](https://github.com/faceping/avalonia-starter) runs as a check-in device too: set `DeviceToken` and `PersonId` in `FaceCheck/App.axaml.cs` (see its README).

If you switch one install from the sandbox key to a device token instead, the two sets of faces stay apart: the app sees only the people synced from the device's list, and your sandbox faces come back (if they're under 24 hours old) when you switch back. Uninstalling removes both.
