Quickstart
Capture the front camera, run a measurement with the iOS SDK and store the result through your backend.
This guide builds a complete measurement screen: your app captures the front camera, the SDK measures on the device, and your backend stores the result. Finish Installation first.
Create the measurement controller
MeasurementController owns the camera and the SDK. It makes every SDK call on one serial
queue — the queue that also receives camera frames — and hands callbacks to the main queue.
import AVFoundation
import NeccessorySDK
final class MeasurementController: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
enum CameraError: Error {
case unavailable
}
let captureSession = AVCaptureSession()
var onUpdate: ((RealtimeUpdate) -> Void)?
var onResult: ((MeasurementResult) -> Void)?
var onFailure: ((Error) -> Void)?
private let queue = DispatchQueue(label: "com.example.measurement")
private var measurement: NeccessoryMeasurement?
func prepare(keyId: String) {
queue.async { [self] in
do {
let measurement = try NeccessoryMeasurement(keyId: keyId)
measurement.onRealtime = { [weak self] update in
DispatchQueue.main.async { self?.onUpdate?(update) }
}
measurement.onResult = { [weak self] result in
DispatchQueue.main.async { self?.onResult?(result) }
}
measurement.onError = { [weak self] error in
DispatchQueue.main.async { self?.onFailure?(error) }
}
self.measurement = measurement
try configureCamera()
captureSession.startRunning()
} catch {
DispatchQueue.main.async { self.onFailure?(error) }
}
}
}
func start() {
queue.async { self.measurement?.start() }
}
func stop() {
queue.async { self.measurement?.stop() }
}
func close() {
queue.async { self.captureSession.stopRunning() }
}
func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
let timestamp = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer))
measurement?.processFrame(pixelBuffer: pixelBuffer, timestampSeconds: timestamp)
}
private func configureCamera() throws {
guard let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) else {
throw CameraError.unavailable
}
let input = try AVCaptureDeviceInput(device: camera)
let output = AVCaptureVideoDataOutput()
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]
output.setSampleBufferDelegate(self, queue: queue)
captureSession.beginConfiguration()
captureSession.sessionPreset = .vga640x480
guard captureSession.canAddInput(input), captureSession.canAddOutput(output) else {
captureSession.commitConfiguration()
throw CameraError.unavailable
}
captureSession.addInput(input)
captureSession.addOutput(output)
output.connection(with: .video)?.videoOrientation = .portrait
captureSession.commitConfiguration()
try camera.lockForConfiguration()
camera.activeVideoMinFrameDuration = CMTime(value: 1, timescale: 30)
camera.activeVideoMaxFrameDuration = CMTime(value: 1, timescale: 30)
camera.unlockForConfiguration()
}
}NeccessoryMeasurement(keyId:)blocks for a few seconds and throwsMeasurementErrorwith the codeinit_failedif the SDK cannot be created. The controller creates it on its queue, never on the main thread.- The camera delivers
kCVPixelFormatType_32BGRAframes in portrait orientation at a fixed 30 fps. - Each frame goes to
processFrame(pixelBuffer:timestampSeconds:)with its presentation time in seconds.
Connect it to your screen
The view controller asks for camera access, shows the preview, coaches the user with
hint and starts the measurement when the user taps Start.
import AVFoundation
import NeccessorySDK
import UIKit
final class MeasurementViewController: UIViewController {
@IBOutlet private var statusLabel: UILabel!
@IBOutlet private var startButton: UIButton!
private let controller = MeasurementController()
private var isMeasuring = false
override func viewDidLoad() {
super.viewDidLoad()
let preview = AVCaptureVideoPreviewLayer(session: controller.captureSession)
preview.frame = view.bounds
preview.videoGravity = .resizeAspectFill
view.layer.insertSublayer(preview, at: 0)
statusLabel.text = "Loading…"
startButton.isEnabled = false
controller.onUpdate = { [weak self] update in
guard let self else { return }
if let hint = update.hint {
statusLabel.text = message(for: hint)
} else if isMeasuring {
statusLabel.text = "\(Int(update.remainingSeconds.rounded(.up))) s left"
} else {
statusLabel.text = "Ready"
}
startButton.isEnabled = !isMeasuring && update.hint == nil
}
controller.onResult = { [weak self] result in
guard let self else { return }
isMeasuring = false
startButton.isEnabled = true
statusLabel.text = result.quality.usable ? "Done" : "No clear reading. Try again."
Task { try await MeasurementUploader.upload(result) }
}
controller.onFailure = { [weak self] _ in
guard let self else { return }
isMeasuring = false
statusLabel.text = "Measurement is unavailable"
}
AVCaptureDevice.requestAccess(for: .video) { [controller] granted in
if granted {
controller.prepare(keyId: "nk_live_…")
}
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
controller.close()
}
@IBAction private func startTapped(_ sender: UIButton) {
isMeasuring = true
startButton.isEnabled = false
statusLabel.text = "Measuring…"
controller.start()
}
private func message(for hint: String) -> String {
switch hint {
case "noFace": return "Look at the camera"
case "faceTooSmall": return "Move closer"
case "faceTooLarge": return "Move back a little"
case "tooDark": return "Find more light"
case "unstable": return "Hold still"
case "lowSnr": return "Hold still and keep the light even"
case "lowSampleRate": return "Camera frame rate is too low"
case "insufficientMetrics": return "Keep going"
default: return "Something went wrong. Try again"
}
}
}Frames reach the SDK as soon as the camera runs, before the user taps Start. Until
start(), the SDK uses them for a pre-check: hint tells you whether the face is in
position and well lit. The screen enables Start once hint is nil. All hint values
are listed in Results.
Send the result to your backend
MeasurementResult is Codable. Encode it with JSONEncoder and post it to your backend:
import Foundation
import NeccessorySDK
enum MeasurementUploader {
static func upload(_ result: MeasurementResult) async throws {
var request = URLRequest(url: URL(string: "https://api.example.com/measurements")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode(result)
let (_, response) = try await URLSession.shared.data(for: request)
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
throw URLError(.badServerResponse)
}
}
}Your backend adds your user ID as userRef and stores the result with
POST /sdk/v1/measurements, signed with your secret. With
the neccessory() signing helper from the main Quickstart:
import express from 'express';
import { neccessory } from './neccessory.mjs';
const app = express();
app.post('/measurements', express.json(), async (req, res) => {
try {
const stored = await neccessory('POST', '/sdk/v1/measurements', {
...req.body,
userRef: req.user.id,
});
res.status(201).json({ id: stored.id });
} catch (error) {
res.status(502).json({ code: error.code, message: error.message });
}
});
app.listen(3000);req.user stands for your own authentication. Use an opaque ID as userRef, not an email
or a name. If the upload fails, keep the result on the device and retry.
Threading
Keep the SDK off the main thread
- Create
NeccessoryMeasurementon a background queue. The initializer blocks for a few seconds. - The class is not thread-safe. Call all its methods from one serial queue, such as your capture queue.
onRealtime,onResultandonErrorrun synchronously on the thread that callsprocessFrame;start_failedarrives on the thread that callsstart(). Dispatch to the main queue before you touch UI, and keep the work inside callbacks short so the camera does not drop frames.
Measurement lifecycle
| Phase | What happens |
|---|---|
Before start() | Frames drive the pre-check. onRealtime reports hint so you can guide the user into position |
start() | A new measurement begins. Any previous measurement is discarded |
| Measuring | onRealtime reports the live heart rate, signal quality, elapsed and remaining time, and hint |
| End | When the configured duration elapses, onResult fires once. The SDK stops collecting, and onRealtime stays silent until the next start() |
stop() | Cancels the current measurement. No callback fires |
Create the instance once and reuse it: each start() begins a fresh measurement.
Measurement duration
A measurement ends on its own after the configured duration. Leave
measurementDurationSeconds at nil to use the recommended duration, or set your own:
let measurement = try NeccessoryMeasurement(
keyId: "nk_live_…",
configuration: .init(measurementDurationSeconds: 60)
)A shorter measurement lowers accuracy, HRV most of all. Show the time left from
remainingSeconds in onRealtime.
Submit from the app
submit(_:) signs a result and posts it to POST /sdk/v1/measurements straight from the
device. It needs the key's secret at initialization; without one it throws no_secret.
let measurement = try NeccessoryMeasurement(keyId: "nk_live_…", secret: secret)
try await measurement.submit(result)A secret in an app can be extracted
Anyone who unpacks your app binary can read the secret and sign requests as your key. Send results through your backend, as in step 3, and keep the secret on the server.
Reference
NeccessoryMeasurement initializer:
| Parameter | Type | Default | Description |
|---|---|---|---|
keyId | String | — | Your key ID |
secret | String? | nil | Key secret. Needed only for submit(_:) |
configuration | NeccessoryMeasurement.Configuration | .init() | measurementDurationSeconds: Double?; nil means the recommended duration |
baseURL | URL | https://neccessory.com | Server that submit(_:) posts to. Keep the default |
Members:
| Member | Description |
|---|---|
processFrame(pixelBuffer:timestampSeconds:) | Pass every camera frame: a kCVPixelFormatType_32BGRA pixel buffer and its presentation time in seconds, always increasing |
start() | Begins a new measurement |
stop() | Cancels the current measurement without a callback |
submit(_:) async throws | Signs a result and stores it with POST /sdk/v1/measurements. Requires secret |
onRealtime | ((RealtimeUpdate) -> Void)? — live updates before and during a measurement |
onResult | ((MeasurementResult) -> Void)? — the final result, once per measurement |
onError | ((MeasurementError) -> Void)? — the measurement cannot run, for example start_failed |
keyId | The key ID passed to the initializer |
Fields, hints and error codes are described in Results.