# .NET MAUI reference

> Every public type in FacePing.Sdk.Maui: setup, enrolment, verification, the camera view and results.

Source: https://docs.faceping.ai/sdk/maui/

Package: [`FacePing.Sdk.Maui`](https://www.nuget.org/packages/FacePing.Sdk.Maui) (NuGet, preview). Starter app: [faceping/maui-starter](https://github.com/faceping/maui-starter). Android 7 (API 24) or later on 64-bit phones (`arm64-v8a`; `x86_64` emulators build too), iOS 15.1 or later. Mac Catalyst and Windows aren't supported: keep just the Android and iOS targets.

Namespaces: `FacePing.Sdk.Maui` for setup, `IFacePing`, `FaceImage` and `FaceCameraView`; `FacePing.Sdk` for results and exceptions, the same on every platform. The package adds `using FacePing.Sdk` to your project for you, so a page only needs `using FacePing.Sdk.Maui;`.

## Setup

```csharp
builder.UseFacePing(o =>
{
    o.SandboxKey = "fp_test_…";                 // sandbox: faces enrolled on the device
    // o.DeviceToken = "fpd_…";                 // or a device token built in (to try a device; pair at runtime in production)
    // o.Region = FacePingRegion.EU;          // your account's region (the default)
});
```

### FacePingOptions

| Property | Type | Default | Notes |
|---|---|---|---|
| `SandboxKey` | `string?` | `null` | A `fp_test_` key from [**Developers → Sandbox keys**](https://app.faceping.ai/developers). |
| `DeviceToken` | `string?` | `null` | A `fpd_` device token for one check-in list (from `POST /v1/lists/{listId}/devices`, or the list's Devices tab), built into the app. Fine for trying a device on your practice list; in production leave it out and call `PairAsync` at runtime. Set this or `SandboxKey`, not both. |
| `Region` | `FacePingRegion` | `EU` | Your account's region, which sets the API address. Today the only value is EU (`https://api-eu.faceping.ai/`). |
| `ApiBaseUrl` | `Uri?` | `null` | Overrides the region's address. UK and US regions are available on request: we give you the address to put here. |
| `PassiveLiveness` | `bool` | `true` | Passive liveness on every check. Turn it off only if your app runs its own liveness check first. |
| `AutoSyncInterval` | `TimeSpan?` | 5 minutes | With a device token (production, or a practice-list device). `null` turns automatic sync off; call `SyncAsync` yourself. In the sandbox the SDK activates and renews its licence itself. |
| `VerifyPolicy` | `VerifyPolicy` | `VerifyPolicy.Default` | How strict verification is. Change only if you know why. |

`UseFacePing` registers `IFacePing` as a singleton. Ask for it in a constructor, or use `IFacePing.Current` where there's no dependency injection.

Setting both `SandboxKey` and `DeviceToken` throws `FacePingSetupException` when the app starts. Setting neither is how a check-in device starts before it's paired: the face models load, and every face check or sync throws `FacePingSetupException` until `PairAsync` has run.

## IFacePing

```csharp
public interface IFacePing
{
    static IFacePing Current { get; }   // for code without dependency injection

    bool IsSandbox { get; }             // true with a SandboxKey; false with a DeviceToken, even for a practice list
    bool IsPaired { get; }              // true once a check-in device has a device token (built in, or PairAsync)
    IReadOnlyCollection<string> EnrolledIds { get; }

    Task<EnrollResult> EnrollAsync(string id, FaceImage photo, CancellationToken ct = default);
    Task<VerifyResult> VerifyLiveAsync(string id, FaceCameraView camera, string? nonce = null, CancellationToken ct = default);
    Task<VerifyResult> VerifyAsync(string id, FaceImage photo, string? nonce = null, CancellationToken ct = default);

    Task<bool> ForgetAsync(string id);
    Task ForgetAllAsync();

    Task<SyncResult> SyncAsync(CancellationToken ct = default);   // sandbox: activate the key; production: fetch faces

    Task<SyncResult> PairAsync(string deviceToken, CancellationToken ct = default);   // check-in devices: run with this token
    Task UnpairAsync();                                             // check-in devices: wipe the faces, forget the token
    event EventHandler<SyncResult>? Synced;                         // after every sync (automatic sync runs with a device token)
}
```

| Method | Notes |
|---|---|
| `EnrollAsync` | Sandbox only. With a device token (production, or a check-in device on your practice list) it throws `InvalidOperationException`: people enrol with consent on your server or through the FacePing widget, and devices get them at their next sync. Replaces any face already stored under `id`. |
| `VerifyLiveAsync` | Runs a live attempt on the camera's frames: match, head turn, match again. Shows prompts in the `FaceCameraView`. Times out after 10 seconds with `NoFace` or the last failure. |
| `VerifyAsync` | One photo, passive liveness only. |
| `nonce` | Check-in devices: a nonce from your server, signed into the result's `SignedResult` so your server can tell the result answers that check. 1 to 128 characters, no control characters (anything else throws `ArgumentException`). See [Signed check results](https://docs.faceping.ai/signed-results/). |
| `ForgetAsync` | With a sandbox key: deletes the face stored under `id` from the device straight away. With a device token (production, or a practice-list device): throws `InvalidOperationException`; remove a person through your server instead, and every device drops them at its next sync. |
| `ForgetAllAsync` | Deletes every face on the device straight away. In production the next sync brings back the people still enrolled. |
| `EnrolledIds` | Who can be verified on this device, as of the last enrol, forget or sync. |
| `SyncAsync` | Production: downloads the latest faces for the device's list; a revoked device wipes its faces. Sandbox: activates the key, or renews its licence when due. Either way it refreshes `EnrolledIds`, so it's a good first call when the app starts. |
| `PairAsync` | Check-in devices: runs with this `fpd_` device token from now on and syncs its list, returning the first sync's result. Call it on every launch with the token your app keeps in secure storage, or once from a pairing screen: see [Pair each device](https://docs.faceping.ai/devices/#pair-each-device). Pairing again with the same token just syncs. A token for another list moves the device: at its first successful sync the previous list's faces are wiped, then the new list's arrive (until then, offline, it keeps the list it has). A mistyped or revoked token throws `FacePingSetupException` and leaves the device unpaired, with no faces; with no connection the result is `Unavailable` and the device syncs when it's back online. Throws `FacePingSetupException` in a sandbox build (a `SandboxKey` in `UseFacePing`). |
| `UnpairAsync` | Check-in devices: wipes the synced faces and forgets the device token and its list, for a device you're retiring or handing back. Moving to another list doesn't need it: pair with that list's token. Clear your saved token too. |
| `IsPaired` | `true` once a check-in device has a device token, built in or from `PairAsync`; `false` in the sandbox and after `UnpairAsync`. |

## FaceImage

What you can pass as a photo. Converts implicitly from each of these:

| From | Example |
|---|---|
| `byte[]` (JPEG or PNG) | `await faceping.EnrollAsync("me", bytes)` |
| `Stream` | `await faceping.EnrollAsync("me", stream)` |
| `FileResult` (from `MediaPicker`) | `await faceping.EnrollAsync("me", await MediaPicker.CapturePhotoAsync())` |
| `FaceCameraView` capture | `await faceping.EnrollAsync("me", await Camera.CaptureAsync())` |

Large photos are scaled down to 1280 pixels on the device before anything else happens.

## FaceCameraView

A front-camera view with a face guide and the liveness prompts ("Turn your head left", "Look back at the camera").

```xml
<fp:FaceCameraView x:Name="Camera" HeightRequest="420" />
```

| Member | Notes |
|---|---|
| `Task<FaceImage> CaptureAsync()` | Takes a still from the live view: upright, as the camera sees it (the preview is mirrored, the picture isn't). Throws `InvalidOperationException` if the camera delivers no picture within 5 seconds. |
| `bool ShowGuide` | The face outline. Default `true`. |
| `string? Prompt` | Set by `VerifyLiveAsync`; bind to it if you draw your own prompts. |
| `FaceGuideState GuideState` | How the guide looks: `Ready` (dashed), `Working` (a scan line), `Match` (green) or `NoMatch` (red). `VerifyLiveAsync` sets it; set it yourself for other steps, for example `Working` while enrolling. |
| `event CameraFailed` | The camera couldn't start: permission refused or no front camera. The message says which. |

Camera permission is requested the first time the view appears. Your app declares it: `android.permission.CAMERA` in AndroidManifest.xml (the package adds it too) and `NSCameraUsageDescription` in Info.plist.

## Results

```csharp
public record EnrollResult(EnrollOutcome Outcome, string Id)
{
    public bool IsEnrolled { get; }   // Outcome == Enrolled
}

public enum EnrollOutcome
{
    Enrolled, NoFace, MultipleFaces, FaceTooSmall, NotLive, LimitReached
}

public record VerifyResult(
    VerifyOutcome Outcome,
    double Similarity,
    double? LivenessScore,
    TimeSpan Elapsed,
    bool IsSandbox,
    string? SignedResult)          // check-in devices: the signed result for your server; null in the sandbox
{
    public bool IsMatch { get; }   // Outcome == Match
}

public enum VerifyOutcome
{
    Match, NoMatch, NotEnrolled, NoFace, LivenessFailed, ChallengeFailed, Expired, LeaseExpired
}

public record SyncResult(
    SyncStatus Status,                  // Ok, Gone, Revoked or Unavailable
    int Enrolled,
    DateTimeOffset? LeaseUntil,         // production: verifies offline until then
    DateTimeOffset? DeleteAfter,
    Signing Signing);                   // Registered, Mismatch or Unknown
```

What a sync status means, with a device token:

| Status | What happened | What the app should do |
|---|---|---|
| `Ok` | The device has the list's latest faces. | Nothing: it verifies offline until the lease runs out. |
| `Gone` | The list is past its deletion date, so the device wiped its copy. | Stop offering face check-in for this list. |
| `Revoked` | The device token was revoked, isn't valid, or its list was deleted, so the device wiped its copy. | Stop offering face check-in, and pair the device again with a new token if it should carry on. |
| `Unavailable` | No connection, or the server couldn't be reached. The device keeps its copy. | Carry on: it verifies offline until the lease runs out, then needs a sync. |

`SignedResult` is set on a check-in device (a device token): every outcome is signed by the device, so your server can prove the check happened. It's `null` in the sandbox, and until the device's first sync. `Signing` says whether FacePing holds the device's signing key: `Registered`; `Mismatch` (the app was reinstalled or its data cleared, so checks still work but signed results won't verify: add the device again); or `Unknown` (before the first sync, and in the sandbox). See [Signed check results](https://docs.faceping.ai/signed-results/).

`LimitReached` means the sandbox already holds 25 faces on this device: forget one first. `LeaseExpired` (production) means the device hasn't synced for longer than its lease, 24 hours by default; it needs a connection before it verifies again.

## EnrollmentPhoto

For [server-side enrolment](https://docs.faceping.ai/server-enrollment/): shrinks a camera photo before your app uploads it to your server. FacePing works at 1280 px, so a 12 MP original only costs upload time; this makes about 1.4 MB into 0.2 to 0.3 MB with the same result, and applies the photo's EXIF orientation. It runs in the FacePing core, with the same decoder as the server.

```csharp
public static class EnrollmentPhoto            // namespace FacePing.Sdk
{
    public const int DefaultQuality = 90;

    // A JPEG, upright, longest side at most 1280 px. Throws ArgumentException if the photo isn't a JPEG or PNG.
    public static byte[] Prepare(byte[] photo, int quality = DefaultQuality);
}
```

## Exceptions

| Exception | When |
|---|---|
| `FacePingSetupException` | The key or token is missing or malformed (neither set, both set, or a sandbox key that doesn't start with `fp_test_`), or the sandbox key couldn't be activated (the first run needs a connection, or the server refused the key). The message says which. A revoked or mistyped device token throws this at a device's first sync; once a device has synced, a revoked token or a deleted list doesn't throw: sync returns `Revoked` and the device wipes its copy. |
| `FacePingModelException` | The face models couldn't load on this device. Send people to your normal entry. |
| `InvalidOperationException` | `FaceCameraView.CaptureAsync` got no picture from the camera within 5 seconds (no permission, or the view isn't on screen), or a call that isn't allowed in this mode, such as `EnrollAsync` or `ForgetAsync` with a device token. The message says which. |

Everything else is a result, not an exception: a face check never throws because someone looked away.
