# Get started with Capacitor

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

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

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 phone or iPhone
Free sandbox key

## Get a sandbox key

Sign up at [app.faceping.ai/signup](https://app.faceping.ai/signup?platform=capacitor) 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 Node 22 or later and a phone with a cable: an Android phone (Android 7 or later, 64-bit) with USB debugging on, the Android SDK and JDK 21 (both come with [Android Studio](https://developer.android.com/studio)), or an iPhone (iOS 16 or later) and a Mac with Xcode 26 or later.

A web app built with Vite and TypeScript, wrapped by Capacitor 8:

```bash
npm create vite@latest facecheck -- --template vanilla-ts
cd facecheck
npm install
npm install @capacitor/core @capacitor/android @capacitor/ios
npm install -D @capacitor/cli
npx cap init FaceCheck com.yourcompany.facecheck --web-dir dist
```

`com.yourcompany.facecheck` is the app id: use one that's yours (iOS signing needs it). Capacitor copies it into the native projects when they're created.

Already have a Capacitor app (Ionic, Angular, React or Vue)? Install the package from [Add FacePing](#add-faceping), then run `npm run build && npx cap sync` instead of `npx cap add` (your native projects already exist), and carry on from [Allow the camera](#allow-the-camera). FacePing works the same in any of them.

First Capacitor app on this machine?

The 10 minutes assume your machine already builds Capacitor apps for your phone. If it doesn't, follow Capacitor's [environment set-up](https://capacitorjs.com/docs/getting-started/environment-setup) (Android Studio, or Xcode on a Mac; both take a while to download).

## Add FacePing

One package from npm. It brings the face models, liveness checks and its own camera screen with it. FacePing for Capacitor is in preview, under the `preview` tag.

Building for Android? Gradle needs JDK 21. If `java -version` shows a newer one, point `JAVA_HOME` at Android Studio's first, in the same terminal: with a newer JDK, `npx cap add android` can print "BUILD FAILED" and then "android platform added!".

```bash
# macOS, Android Studio's JDK
export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"
```

Then add the package and the native projects:

```bash
npm install @faceping/capacitor@preview
npm run build
npx cap add android
npx cap add ios
```

`npx cap add` creates the native `android` and `ios` projects. Android gets the FacePing SDK from Maven Central; iOS gets it as a Swift package from [faceping/faceping-ios](https://github.com/faceping/faceping-ios). See [npm](https://www.npmjs.com/package/@faceping/capacitor) for the latest version. The first build downloads Microsoft's ONNX Runtime and the face models (a few tens of MB), and they add about the same to your app.

## Allow the camera

**iOS.** Set the iOS version to 16.0 for the whole project, not just the app target: `npx cap sync` reads the project's setting, and with only the target changed the build fails. From the project folder:

```bash
sed -i '' 's/IPHONEOS_DEPLOYMENT_TARGET = 15.0;/IPHONEOS_DEPLOYMENT_TARGET = 16.0;/g' ios/App/App.xcodeproj/project.pbxproj
```

(In Xcode, that's **iOS Deployment Target** on the **App** project's **Build Settings** and **Minimum Deployments** on the **App** target.) Then open the project with `npx cap open ios`, and on the **App** target's **Info** tab add **Privacy - Camera Usage Description** (`NSCameraUsageDescription`) with a sentence such as "FaceCheck uses the camera to verify your face." iOS shows it to the person before the camera turns on, and stops the app without it. Then run `npx cap sync ios`.

**Android.** The FacePing library declares the camera permission (and `INTERNET`, to activate your key). Do turn off backup: in `android/app/src/main/AndroidManifest.xml`, change `android:allowBackup="true"` to `android:allowBackup="false"`. FacePing encrypts its face data 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). Backups need rules too: Android 12 and later also copy data when someone moves to a new phone. Add `android:dataExtractionRules="@xml/data_extraction_rules"` and `android:fullBackupContent="@xml/backup_rules"` to the same `<application>` tag, and create the two files:

```xml title="android/app/src/main/res/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="faceping.keys.xml" />
    </cloud-backup>
    <device-transfer>
        <exclude domain="file" path="faceping/" />
        <exclude domain="sharedpref" path="faceping.keys.xml" />
    </device-transfer>
</data-extraction-rules>
```

```xml title="android/app/src/main/res/xml/backup_rules.xml"
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
    <exclude domain="file" path="faceping/" />
    <exclude domain="sharedpref" path="faceping.keys.xml" />
</full-backup-content>
```

FacePing runs on 64-bit phones only, so build Android for those alone: otherwise the app also lists 32-bit ABIs it can't run on, and a 32-bit phone would install it and then fail. In `android/app/build.gradle`, inside `defaultConfig`:

```gradle
ndk {
    abiFilters 'arm64-v8a', 'x86_64'
}
```

(`x86_64` is for the Android emulator. For the Play Store, an App Bundle gives each phone only its own, so it costs nothing there. For a release APK you hand out yourself, change the line to `abiFilters 'arm64-v8a'` before you build it, to save about 25 MB.)

The camera screen asks the person for the camera the first time it opens.

**Why iOS 16?** The FacePing iOS SDK needs iOS 15.1, and Capacitor's Swift Package Manager setup rounds the app's target down to a whole version. Apps that use CocoaPods can stay on iOS 15.1. See [iOS versions](https://docs.faceping.ai/sdk/capacitor/#ios-versions).

## Turn FacePing on

Set FacePing up once, when the app starts, with your sandbox key. Add this to `src/main.ts`, under the imports:

```ts title="src/main.ts"
import { FacePing } from '@faceping/capacitor';

// Starts loading the face models in the background, so the first check is quick.
FacePing.init({ sandboxKey: 'fp_test_…' }).catch((e) => console.warn(e.message));
```

To keep the key out of your code, put `VITE_FACEPING_SANDBOX_KEY=fp_test_...` in `.env.local` (the Vite template keeps it out of git) and use `import.meta.env.VITE_FACEPING_SANDBOX_KEY`, as the starter app does.

## Add the screen

Two buttons: one enrols your face on the phone, the other verifies it. Each opens FacePing's camera screen, which closes itself when the check is done. Replace `src/style.css` with just enough style to look like an app:

```css title="src/style.css"
#app { display: grid; gap: 12px; padding: 64px 24px; font: 17px system-ui, sans-serif; }
button { font: inherit; font-weight: 600; padding: 16px; border-radius: 12px; border: 1.5px solid #2563eb; background: none; color: #2563eb; }
button.primary { background: #2563eb; color: #fff; }
```

Then replace `src/main.ts` (the `init` call from [Turn FacePing on](#turn-faceping-on) is at the top):

```ts title="src/main.ts"
import './style.css';
import { FacePing } from '@faceping/capacitor';

// Starts loading the face models in the background, so the first check is quick.
FacePing.init({ sandboxKey: 'fp_test_…' }).catch((e) => console.warn(e.message));

document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
  <p id="status"></p>
  <button id="enroll">Enrol my face</button>
  <button id="verify" class="primary">Verify</button>`;

const status = document.querySelector<HTMLParagraphElement>('#status')!;

// For example no connection on the very first run (the sandbox key is activated once), or the camera screen closed.
const act = (action: () => Promise<string>) =>
  action().then((text) => (status.textContent = text), (e: Error) => (status.textContent = e.message));

document.querySelector('#enroll')!.addEventListener('click', () =>
  act(async () => {
    const result = await FacePing.enroll('me'); // opens the camera screen and takes a photo
    return result.isEnrolled ? 'Enrolled. Now tap Verify.' : `Try again: ${result.outcome}`;
  }),
);

document.querySelector('#verify')!.addEventListener('click', () =>
  act(async () => {
    // A live check: matches your face, then asks you to turn your head (liveness).
    const result = await FacePing.verifyLive('me');
    const time = (result.elapsedMs / 1000).toFixed(2);
    return result.isMatch ? `Match · ${time} s` : `Try again: ${result.outcome}`;
  }),
);
```

## Run it on your phone

Plug your phone in, build the web app, copy it into the native projects and run one of these (Capacitor asks which device):

```bash
npm run build && npx cap sync
npx cap run android
npx cap run ios
```

A debug build is fine for trying it: the FacePing core inside the SDK is already compiled for speed, whichever build you run. For a release build (the app as you'd ship it), use Android Studio's **Build → Generate Signed App Bundle or APK** with your own upload key (`npx cap open android`), and Xcode's **Product → Archive** (`npx cap open ios`). On iOS, pick your team in Xcode under **Signing & Capabilities** first (`npx cap open ios`), or run the app from Xcode. The first time, turn on **Developer Mode** on the iPhone (**Settings → Privacy & Security → Developer Mode**).

The first run needs a connection, to activate your sandbox key. Tap **Enrol my face** and take a photo, then tap **Verify** and turn your head when asked: 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.

**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/capacitor-starter): github.com/faceping/capacitor-starter
- [How the SDK works](https://docs.faceping.ai/sdk/): Liveness, storage, sandbox limits
- [Capacitor reference](https://docs.faceping.ai/sdk/capacitor/): Every type and method
- [@faceping/capacitor on npm](https://www.npmjs.com/package/@faceping/capacitor): Versions and changelog

## 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. Capacitor writes the app id into the native projects only when it creates them, so copy the project folder without `android`, `ios` and `node_modules`, and in the copy's `capacitor.config.ts` set its own `appId` (for example `com.yourcompany.facecheck.device`) and `appName` (`FaceCheck Device`). Put the token in the copy's `.env.local` as `VITE_FACEPING_DEVICE_TOKEN=fpd_…`, then repeat [Add FacePing](#add-faceping) and [Allow the camera](#allow-the-camera) in the copy (`npm install`, `npm run build`, `npx cap add android`, `npx cap add ios`, then the iOS and Android settings).
5. Replace the copy's `src/main.ts`. It sets FacePing up with the device token, verifies the person you enrolled, syncs when the app opens and shows the result of every sync after that. People enrol on the server, not in the app (`enroll` throws a `FacePingError` with the code `invalidOperation` on a device), so there's no enrol button:

```ts title="src/main.ts (device build)"
import './style.css';
import { FacePing } from '@faceping/capacitor';

const personId = 'ACME-000123'; // the person you enrolled

// A device token instead of the sandbox key. A setup problem shows on screen when the app syncs.
const ready = FacePing.init({ deviceToken: import.meta.env.VITE_FACEPING_DEVICE_TOKEN });
ready.catch(() => {});

document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
  <p id="synced"></p>
  <p id="status"></p>
  <button id="verify" class="primary">Verify</button>`;

const synced = document.querySelector<HTMLParagraphElement>('#synced')!;
const status = document.querySelector<HTMLParagraphElement>('#status')!;

// Every sync, now and the automatic ones every few minutes, updates the line
// ('revoked': the token was revoked, mistyped or its list deleted).
FacePing.addListener('synced', (r) => (synced.textContent = `${r.enrolled} people synced (${r.status})`));
ready.then(() => FacePing.sync()).catch((e: Error) => (synced.textContent = e.message));

document.querySelector('#verify')!.addEventListener('click', () =>
  FacePing.verifyLive(personId).then(
    (result) =>
      (status.textContent = result.isMatch
        ? `Match · ${(result.elapsedMs / 1000).toFixed(2)} s`
        : result.outcome === 'notEnrolled'
          ? `${personId} isn't on this device yet: enrol them, then wait for the next sync.`
          : `Try again: ${result.outcome}`),
    (e: Error) => (status.textContent = e.message),
  ),
);
```

6. Run it with `npm run build && npx cap sync` and `npx cap run android` (or `ios`) in the copy. It downloads the list's faces at start-up and every few minutes after; the top 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/capacitor-starter) runs as a check-in device too: put `VITE_FACEPING_DEVICE_TOKEN` and `VITE_FACEPING_PERSON_ID` in its `.env.local` (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.
