Skip to main content

iOS with Swift

Evaluate the Swift source package and fail-closed signed-license verifier before a certified XCFramework is published.

SDK 0.1.0-RC5 · Preview

Status: Preview Minimum deployment target: iOS 15 Distribution: Source only

VisionScan includes a Swift facade, AVFoundation helpers, fail-closed JWS verification, and a real native MatrixScan C bridge. Windows Swift source compilation and real-image bridge tests are verified; Apple SDK compilation and physical camera validation remain gates. RC2 does not publish a certified XCFramework or remote Swift package. Use this guide for API evaluation, not a production claim.

Preview contract map

Contract Input Result RC2 boundary
registerPublicKey Trusted key ID, exact RS256/ES256 algorithm, SecKey Key becomes eligible for JWS verification Never register a key received from an untrusted payload.
applySignedLicenseJws Compact JWS plus expected tenant and device IDs VisionScanEntitlementEvaluationResult Bad crypto, claims, binding, revision, expiry, revocation, or grace deny access. Caller-created licenses are always denied.
VisionScanSession lifecycle Matrix mode, verified entitlement manager, start , sized luma frames, pause , close Real native stable observations and state callbacks Source preview; Apple compilation and camera certification pending.
latestMatrixFrame Last successful sized frame Native track IDs, input-pixel quads, stability, duplicate/count/target/pick state Private barcode content; not telemetry.
setTargets , setPickState Raw target Data , native track ID and typed pick state Native Find/Pick state transitions SDK owns matching/state; invalid transitions throw.
usageSnapshot Active native session Content-free, non-consuming admission counters Does not enroll, persist, reset or upload automatically.
VisionScanMatrixTelemetry Verified manager/session, HTTPS origin, SDK version, encrypted storage, token provider Worker-owned checkpoint, durable retry, acknowledgment Opt-in; Apple crypto/TLS and enrolled delivery require runtime validation.

The portal renders these definitions from contracts/sdk-public-contracts.json ; the Swift source remains authoritative for exact types during preview evaluation.

Add the local package

Reference the checked-out host-ios directory from the consuming package:

dependencies: [
    .package(path: "../PrxVision/host-ios")
]

The package product is VisionScan and requires Swift tools 5.9. Do not substitute an invented CocoaPods, Carthage, or remote Swift Package URL.

Build the native dependency first. On macOS with Xcode and CMake, run bash scripts/test-native-host-apple.sh from the SDK repository. This compiles macOS native/Swift tests, arm64 iOS device/simulator native frameworks and Swift source, then creates an unsigned native XCFramework. The script is also exposed by the manual native-host-apple.yml workflow. Neither execution nor certified packaging is claimed until a Mac actually runs it.

VISIONSCAN_NATIVE_LIBRARY_DIR points to the native library directory for macOS/Windows source builds. VISIONSCAN_NATIVE_FRAMEWORK_DIR selects the iOS framework directory instead; set it when resolving the local package and embed the matching framework in the host application. The C shim references the canonical header from the repository checkout; this is not a standalone remote package.

Apply a signed license

Fetch the license JWS and JWKS through authenticated host networking. Select the JWK matching the JWS kid , convert it to a Security-framework SecKey , and register the exact algorithm.

import VisionScan

let verifier = VisionScanJwsVerifier()
verifier.registerPublicKey(kid: keyId, algorithm: .rs256, key: secKey)

let manager = VisionScanEntitlementManager(verifier: verifier)
let entitlement = manager.applySignedLicenseJws(
    signedLicenseJws,
    expectedTenantId: tenantId,
    expectedDeviceId: deviceId
)

guard entitlement.isAllowed else {
    throw LicenseError.denied(entitlement.denialReason)
}

applySignedLicense rejects caller-created claim objects. The verifier checks algorithm, key ID, signature, issuer, audience, timestamps, tenant, device, and monotonic revision before storing a license.

Exercise the session lifecycle

let session = VisionScanSession(
    configuration: .init(executionMode: .liveStreaming, matrixMode: .ar),
    entitlementManager: manager
)

try session.start()
// The capture adapter borrows the luma plane with its explicit byte count.
// Or call processLumaFrame(data:width:height:stride:timestampNs:).
session.pause()
session.close()

processLumaFrame calls the native locator, decode scheduler and tracker, not a simulation. Use byteCount with pointers, or Data ; the deprecated unsized overload fails closed. Frames require increasing monotonic nanosecond timestamps and fixed dimensions for a session. Create a new session on resolution or mode changes. Methods serialize native access; feed frames on a worker queue and marshal UI callbacks to the UI thread. Serialize configuration/delegate access with the capture lifecycle.

Modes are .batch , .ar , .count , .find and .pick ; these MatrixScan modes use the live native scheduler, not a still-image throughput API. Non-default preprocessing profiles and non-live execution modes are rejected until their configuration bridge is implemented. The neutral bridge does not synthesize pharmacy fields.

Draw native quads from latestMatrixFrame.tracks after applying the real preview crop/rotation/mirroring transform. Quads are input-luma pixels, not normalized UI coordinates. Use count for mode-specific count state; telemetry counts accepted admissions, never visible boxes or redraws. latestMatrixFrame clears on failed frame processing and close, avoiding stale overlays.

Find/Pick targets use raw byte Data ; decoded BYTE_LATIN1 payload scalars map one-to-one to bytes, not UTF-8. Start the session, call setTargets , and use setPickState(trackId:state:) for stable matched Pick tracks. Missing/unmatched IDs and invalid transitions throw.

Security and lifecycle checks

  • Keep bearer tokens, compact JWS values, image bytes, and private keys out of logs.
  • Treat ERR_JWS_UNKNOWN_KEY as a JWKS refresh signal, not a reason to disable verification.
  • Reject expired, revoked, cross-tenant, cross-device, and rollback licenses.
  • Close capture and session resources when the app backgrounds or the user signs out.

Native usage snapshot codec

VisionScanMatrixUsageSnapshot validates bounded native visionscan-matrix-usage/v1 JSON and re-encodes only its content-free fields:

let usage = try VisionScanMatrixUsageSnapshot(nativeJSON: nativeUsageJSON)
let diagnosticPayload = try usage.jsonData()

Supply UTF-8 bytes without the C ABI's terminating NUL, from a real native session only. The codec rejects unknown fields, unknown histogram buckets, unsupported modes/versions, negative or out-of-range counters, and inconsistent totals. It is not a general untrusted JSON validator (Foundation does not expose duplicate object keys).

Call session.usageSnapshot() to read active native counters. While a reporter holds a checkpoint, this snapshot excludes the pending window. The codec performs no enrollment, storage, or upload. Barcode result JSON must never be submitted as telemetry.

Opt-in secure usage delivery

Use the same manager that verified the backend enrollment JWS. Device IDs must be registered UUIDs, not hardware serials. Configure one reporter/storage per session:

let directory = try FileManager.default.url(for: .applicationSupportDirectory,
    in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("VisionScanTelemetry")
let storage = try VisionScanAppleTelemetryStorage(directory: directory,
    keychainService: "com.yourcompany.visionscan.telemetry", account: enrolledDeviceId)
let telemetry = try VisionScanMatrixTelemetry(session: session,
    entitlementManager: manager, controlPlaneOrigin: approvedBackendOrigin,
    sdkVersion: installedSdkVersion, storage: storage,
    tokenProvider: { try authenticatedHost.refreshTelemetryToken() })
telemetry.flush()
// Stop the camera before finishing; completion runs on the reporting worker.
telemetry.finish { status in
    // Marshal UI work to main. Recover paused sessions on storage/full/identity failure.
}

Keep the session, storage and reporter alive together. Do not call session.close() before finish persists its last window. A new reporter restores the same outbox after restart. Use a separate directory per tenant/license; never delete a failed spool to make upload succeed. A killed process can lose its not-yet-persisted live window: an in-memory checkpoint is not a disk checkpoint.

The core holds one pending window while new frames continue accumulating. The host acknowledges only after an atomic encrypted save. Full queues and failed writes retain counters. JSON, crypto, disk and HTTPS run outside camera processing on one worker. Queue: at most 128 events; upload: 50; request: 512 KiB; response: 256 KiB.

VisionScanAppleTelemetryStorage uses authenticated AES-GCM with a non-synchronizing, device-only Keychain key, atomic writes, file/directory synchronization, restricted permissions and a single-writer lock. Missing keys/tampering fail closed; no plaintext fallback exists. Host token refresh runs on the worker and tokens are never persisted. Default TLS trust is retained; redirects/cookies are disabled and timeouts/backoff bounded.

Requests use /api/v1/sdk-telemetry/ingest . Tenant/license IDs and barcode contents are absent from the wire envelope. Backend claims and enrolled-device authorization derive ownership. Retry IDs survive restart. Accepted/Duplicate outcomes remove events only after a durable acknowledgment save; Rejected surfaces backendRejected , not success. Identity changes latch the reporter stopped.

Windows Swift tests exercise explicit test storage/transport seams and real native checkpoints. They do not execute Apple crypto or prove TLS delivery. Apple build/runtime, signed distribution and enrolled device-to-tenant projection remain acceptance gates.

Path to supported release

A supported iOS release still requires Apple builds, a signed XCFramework, reproducible release packaging, checksum and signature publication, a tenant download grant, physical-device certification, a sample app, compatibility evidence, secure telemetry delivery, and release-channel support policy.

Support matrix

Full API contract reference

Public contract reference

These are the callable methods and HTTP operations used by this guide. Inputs, results, lifecycle rules, and denial behavior are part of the versioned customer contract.

iOS signed-license preview

The source preview verifies JWS claims with Apple Security and does not trust caller-created licenses.

VisionScanEntitlementManager.applySignedLicenseJws(_:expectedTenantId:expectedDeviceId:nowEpochSeconds:)

method

Verify a backend-issued compact JWS and admit its device-bound entitlement claims.

Inputs for VisionScanEntitlementManager.applySignedLicenseJws(_:expectedTenantId:expectedDeviceId:nowEpochSeconds:)
InputTypeRequiredMeaning
jwsStringYesBackend-signed compact JWS.
expectedTenantIdStringYesAuthenticated tenant binding.
expectedDeviceIdStringYesActivated device binding.
Result
VisionScanEntitlementEvaluationResult with allow/deny, state, tier, remediation, and correlation metadata.
Lifecycle
Register the matching trusted public key before applying a JWS; reapply on refresh or revision change.
Trust boundary
The deprecated object-taking applySignedLicense method always denies caller-created claims.
Failure behavior
  • Missing Apple Security crypto, unknown key, bad signature, claim mismatch, expiry, revocation, rollback, or grace expiry deny access.

iOS session preview

Swift consumes the real native MatrixScan bridge; Windows source tests are verified, Apple compilation and certified binaries remain gated.

VisionScanSession.init(configuration:entitlementManager:) -> start() -> processLumaFrame(data:width:height:stride:timestampNs:) -> usageSnapshot() -> pause() -> close()

method

Exercise the Swift session and AVFoundation integration lifecycle.

Inputs for VisionScanSession.init(configuration:entitlementManager:) -> start() -> processLumaFrame(data:width:height:stride:timestampNs:) -> usageSnapshot() -> pause() -> close()
InputTypeRequiredMeaning
configuration.executionModeExecutionModeYesliveStreaming is bridged; batchThroughput/highResolutionRescue and non-default preprocessing profiles are rejected until their configuration bridge is implemented.
luma frameData or sized pointerYesExplicit byte count, fixed luma dimensions and increasing monotonic nanosecond timestamps; verified scan entitlement required.
Result
Real native stable barcode observations, latestMatrixFrame tracks/count/geometry/target/pick state and separate content-free usage snapshots.
Lifecycle
Start once, pause/resume around capture lifecycle, and close deterministically.
Trust boundary
Use for API evaluation only until signed XCFramework packaging and physical-device certification are complete.
Failure behavior
  • Invalid descriptors, unsupported configuration and unverified entitlements fail closed.
  • Windows Swift tests do not certify Apple camera, Security or device execution.

VisionScanMatrixUsageSnapshot.init(nativeJSON: Data) throws; jsonData() throws -> Data

method

Validate and round-trip content-free native visionscan-matrix-usage/v1 snapshots; not an automatic telemetry reporter.

Inputs for VisionScanMatrixUsageSnapshot.init(nativeJSON: Data) throws; jsonData() throws -> Data
InputTypeRequiredMeaning
nativeJSONDataYesBounded UTF-8 native snapshot without the terminating C NUL; no image, payload, geometry, or identity fields.
Result
Immutable typed counters for Batch, AR, Count, Find, or Pick and a closed symbology histogram.
Lifecycle
Read active counters through usageSnapshot; opt-in VisionScanMatrixTelemetry reserves and durably acknowledges separate windows. Enrolled delivery still requires runtime validation.
Trust boundary
No tenant override, keys, tokens, barcode values, or capture bytes. This source codec is not device-to-tenant delivery certification.
Failure behavior
  • Unknown/missing fields, invalid versions/modes, negative or out-of-range counters and inconsistent totals throw.
  • Foundation duplicate-key detection is not provided; Apple compilation and XCTest remain acceptance gates.

VisionScanSession.setTargets([Data]); setPickState(trackId:state:); setScreenScanMode(Bool); latestMatrixFrame: VisionScanMatrixFrame?

method

Expose native target matching, pick transitions and SDK-owned stable tracks to hosts.

Inputs for VisionScanSession.setTargets([Data]); setPickState(trackId:state:); setScreenScanMode(Bool); latestMatrixFrame: VisionScanMatrixFrame?
InputTypeRequiredMeaning
targets[Data]NoAt most 256 raw byte targets, each 1..4096 bytes; use native track IDs for pick.
Result
Copied native targets and typed MatrixScan track/count state in input-luma pixel space, never fabricated UI boxes.
Lifecycle
Start before controls; serialize configuration/capture lifecycle. A new session is required for mode or resolution changes.
Trust boundary
Matrix frame/track payloads are private scan content and must never enter telemetry.
Failure behavior
  • Oversized or empty target values, unknown or unmatched pick tracks and closed sessions throw.

VisionScanMatrixTelemetry.init(session:entitlementManager:controlPlaneOrigin:sdkVersion:storage:maximumQueuedEvents:reportIntervalSeconds:tokenProvider:) throws; flush(completion:); finish(completion:)

method

Deliver opt-in, content-free native usage through a bounded durable outbox using backend-verified enrollment.

Inputs for VisionScanMatrixTelemetry.init(session:entitlementManager:controlPlaneOrigin:sdkVersion:storage:maximumQueuedEvents:reportIntervalSeconds:tokenProvider:) throws; flush(completion:); finish(completion:)
InputTypeRequiredMeaning
storageVisionScanMatrixTelemetryStorageYesApple hosts use VisionScanAppleTelemetryStorage: Keychain key and authenticated AES-GCM, no plaintext fallback.
Result
Typed ready/uploaded/retry/authorization/rejection/identity/full/storage/closed states; stable replay IDs and strict per-event acknowledgments.
Lifecycle
Keep session/storage/reporter alive. Stop capture, then finish to persist the last native window before closing. Storage/full/identity failure preserves the paused session.
Trust boundary
Tenant is backend-derived; no raw license, token, barcode or frame content is persisted or transmitted. Transport retains default TLS trust and denies redirects.
Failure behavior
  • Unverified enrollment, non-HTTPS origins and invalid configuration throw.
  • Corrupt or foreign outboxes fail closed. Apple crypto/TLS and enrolled delivery are unverified external gates.