# iOS

> Run the checkup in a native iOS app, by loading the checkup's page in a WKWebView: not verified on devices yet.
>
> Preview: proposed, may change.

There is no native iOS SDK. A native iOS app runs the checkup by loading YOU(th)'s checkup page in a
`WKWebView`: your app sends it your key when it says `ready`, and receives the result as a message.
There is no page of your own and no iframe, so the script of the [Web SDK](/docs/sdks/web) is not
used: your app speaks the [messages](/docs/sdks/web/reference#messages) itself.

> **Not verified yet:** YOU(th) has not verified this setup on devices. Its steps and its error
> code `DELIVERY_NOT_ALLOWED` may change. Tell your YOU(th) contact before you ship it.

## What it needs

- **A key and the checkup's address**, as for the [Web SDK](/docs/sdks/web#what-your-page-needs).
- **Web views switched on for your organization.** Ask your YOU(th) contact: without it, the checkup
  ends with `DELIVERY_NOT_ALLOWED`. In a web view the checkup cannot see which app shows it, so your
  organization's list of origins does not limit who uses your key there. Your monthly limits and
  revoking the key do.
- **iOS 18 or later.** A web view runs the Safari of its iOS version, and the checkup needs
  Safari 18. On an older iOS, do not offer the checkup.
- **`NSCameraUsageDescription`** in your app's `Info.plist`, and `NSMicrophoneUsageDescription` if
  you run a voice checkup.
- **A plan for App Review**, which looks closely at apps that run a checkup: see
  [App Store and Google Play](/docs/sdks/app-stores).

## Show the checkup

Register a message handler named `youth` before the page loads: the checkup finds it by that name,
and never says `ready` without it. Load the checkup's address with `load(_:)`, never an HTML
string, because the checkup needs the headers its address sends. Your key goes in `init`, never in
the address.

```swift
import UIKit
import WebKit

final class CheckupViewController: UIViewController, WKScriptMessageHandler, WKUIDelegate {
    private static let checkupHost = "sdk.youth-platform.io"
    /// Your key, fetched from your server before this screen opens.
    var apiKey = ""
    private var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let configuration = WKWebViewConfiguration()
        configuration.allowsInlineMediaPlayback = true
        configuration.mediaTypesRequiringUserActionForPlayback = []
        configuration.userContentController.add(self, name: "youth")

        webView = WKWebView(frame: view.bounds, configuration: configuration)
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        webView.uiDelegate = self
        view.addSubview(webView)
        webView.load(URLRequest(url: URL(string: "https://\(Self.checkupHost)/embed.html")!))
    }

    // Messages from the checkup: only from its own page.
    func userContentController(
        _ userContentController: WKUserContentController,
        didReceive message: WKScriptMessage
    ) {
        guard
            message.frameInfo.isMainFrame,
            message.frameInfo.securityOrigin.host == Self.checkupHost,
            let body = message.body as? [String: Any],
            let type = body["type"] as? String
        else { return }

        let payload = body["payload"] as? [String: Any]
        switch type {
        case "ready":
            send(type: "init", payload: ["apiKey": apiKey])
        case "result":
            let biomarkers = payload?["biomarkers"] as? [[String: Any]] ?? []
            save(biomarkers)
        case "error":
            showError(payload?["code"] as? String)
        default:
            break // `initialized`, `progress`, and types added later.
        }
    }

    // Messages to the checkup.
    private func send(type: String, payload: [String: Any]) {
        let message: [String: Any] = ["v": 2, "type": type, "payload": payload]
        guard
            let data = try? JSONSerialization.data(withJSONObject: message),
            let json = String(data: data, encoding: .utf8)
        else { return }
        webView.evaluateJavaScript("window.postMessage(\(json), '*')")
    }

    // The camera and the microphone: only for the checkup's page.
    func webView(
        _ webView: WKWebView,
        requestMediaCapturePermissionFor origin: WKSecurityOrigin,
        initiatedByFrame frame: WKFrameInfo,
        type: WKMediaCaptureType,
        decisionHandler: @escaping (WKPermissionDecision) -> Void
    ) {
        decisionHandler(origin.host == Self.checkupHost ? .grant : .deny)
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isBeingDismissed || isMovingFromParent {
            webView.configuration.userContentController.removeScriptMessageHandler(forName: "youth")
        }
    }
}
```

- **The settings** in `init` are the Web SDK's: the [person](/docs/sdks/web#tell-it-about-the-person),
  the language, the checkup. For another measurement, send `checkup` with the new settings.
- **The results** arrive in `result`, as [Results](/docs/sdks/results) describes them.
- **Errors.** The checkup does not show them: tell the person yourself. The
  [reference](/docs/sdks/web/reference#errors) lists the codes. After an error during a measurement
  the person can start again; if `init` fails, close the screen.
- **A Close button** is yours to add: the checkup has none.

## Keep it safe

- Anything built into an app can be read out of it, and no origin limits a key in a web view. Fetch
  the key from your server rather than building it in.
- The results are health data: do not log them.
- Check the host in the message handler and in the permission callback, as above.
