コンテンツにスキップ

AI Data Tasks

Show your users short AI data tasks inside your app, such as picking the better of two answers. The SDK carries the task screens as one HTML page, ContributionPage.html. Your app shows it in a WKWebView and answers four calls from it. The page fetches a task from the project the user picked, shows the consent screen and the task, and sends the answer with a proof that the SDK signs. Your app never sees the task, the answer, the score or the proof.

When to use it

  • Your app rewards its users for completing tasks, for example from an "Earn rewards" button
  • DEA has projects open for your app

Prerequisites

  • The SDK is installed and started with your appId and appKey. See the Quick Start and Accounts and keys. The samples use the Quick Start's Dea.sdk holder.
  • attest() answered .passed. DEA refuses a task request signed by a key it has not registered.
  • An app user id for each user. It is required: the project list and every task carry it as publisherUserId. See App user ids.
  • import DeaBase beside import DeaSDK: ContributionHosts is in DeaBase.

How a task runs

Step Your app The page
1 Lists the projects open to the user, and shows them in its own screen
2 Opens a screen with a WKWebView, and loads the page for the picked project Asks for its boot values
3 Delivers the boot values Fetches a task, and shows the consent screen when DEA asks for it, then the task
4 Answers the page's calls: ready, attest, signRequest, signContribution Sends the answer to DEA
5 Closes the screen when the outcome arrives Posts one outcome

Usage

1. List the projects

The page runs a task on one project, which the user picks first. The project list is not part of the page: your app requests it from DEA and shows it.

Item Value
Request POST, to ContributionHosts.apiBase followed by /api/tasks/projects
Headers Content-Type: application/json, Accept: application/json, and X-App-Key with the SDK's appKey
Body {"h_proof": "<signed request>"}, signed by signRequest(eventType: "projects", claims:)
Claims to sign publisher_user_id: your app user id. platform: ios. sdk_version: sdkVersion
Answer 200 {"projects": [...]}. Each project has project_id, name, pattern_id (the task type) and pattern_name. Show them in this order
Answer 204 No project is open to this user
Another answer Refused. The body's errorCode says why
import DeaBase
import DeaSDK
import Foundation

enum ProjectList {
    enum Failure: Error {
        case notStarted
        case notSigned(String)
        case noAnswer(Error)
        case refused(status: Int, body: String)
    }

    /// The projects open to this user. Blocking: call it off the main thread.
    static func load(userId: String) throws -> [[String: Any]] {
        guard let dea = Dea.sdk else { throw Failure.notStarted }
        let claims: [String: Any] = [
            "publisher_user_id": userId,
            "platform": "ios",
            "sdk_version": sdkVersion,
        ]
        guard let proof = dea.signRequest(eventType: "projects", claims: claims) else {
            throw Failure.notSigned(dea.lastRequestRefusal ?? "")
        }

        var request = URLRequest(url: URL(string: ContributionHosts.apiBase + "/api/tasks/projects")!)
        request.httpMethod = "POST"
        request.timeoutInterval = 15
        request.httpBody = try JSONSerialization.data(withJSONObject: ["h_proof": proof])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue(dea.appKey, forHTTPHeaderField: "X-App-Key")

        let done = DispatchSemaphore(value: 0)
        var answer: (Data?, URLResponse?, Error?) = (nil, nil, nil)
        URLSession.shared.dataTask(with: request) { data, response, error in
            answer = (data, response, error)
            done.signal()
        }.resume()
        done.wait()

        if let error = answer.2 { throw Failure.noAnswer(error) }
        let status = (answer.1 as? HTTPURLResponse)?.statusCode ?? 0
        let data = answer.0 ?? Data()
        switch status {
        case 200:
            let body = try JSONSerialization.jsonObject(with: data) as? [String: Any]
            return body?["projects"] as? [[String: Any]] ?? []
        case 204:
            return [] // no project is open to this user
        default:
            throw Failure.refused(status: status, body: String(decoding: data, as: UTF8.self))
        }
    }
}

2. Load the page

Load ContributionPage.html into the WKWebView as a string, with ContributionHosts.apiBase as its base URL:

web.loadHTMLString(ContributionPage.html, baseURL: URL(string: ContributionHosts.apiBase))

The base URL is required. The page hashes the task and the answer with Web Crypto, which works only in a secure context, and it sends its requests to its own origin. With no base URL, or another one, the page stops with PAGE_INSECURE, or DEA refuses its requests.

ContributionHosts holds the hosts this build of the SDK talks to. Your app passes them to the page in the boot message:

Constant Boot value What it is
ContributionHosts.apiBase apiBase DEA's API origin, and the page's base URL
ContributionHosts.widgetOrigin widgetOrigin The origin the task's widget is downloaded from
ContributionHosts.mediaOrigin mediaOrigin The origin of the task's images

3. Install the bridge

The page and your app talk through two functions. Each takes one JSON object, as a string.

Function Direction Who defines it
window.deaHost.post(json) Page to app Your app, before the page's own script runs
window.deaPage.deliver(json) App to page The page. Your app calls it with evaluateJavaScript

On iOS:

  1. Add a script message handler to the web view's WKUserContentController.
  2. Add a WKUserScript that defines window.deaHost, injected at .atDocumentStart in the main frame only. It posts to the handler with a random key in front of each message, a new key for each load.
  3. Drop every message without that key, and every message that does not come from the main frame (message.frameInfo.isMainFrame): the handler is visible to every frame of the page, the task runs in a frame of its own, and only the page's own script has the key.
  4. Let the web view navigate only to about:, data: and ContributionHosts.apiBase.

4. Answer the page

Message Direction What your app does
{"t": "ready"} Page to app Deliver the boot message. The page sends ready every 100 ms until the boot message arrives
{"t": "boot", ...} App to page Starts the first task. See the boot values below
{"t": "call", "id", "method", "args"} Page to app Deliver {"t": "result", "id", "value"} with the answer below, or {"t": "error", "id", "message"}. Answer each call within 30 seconds
{"t": "event", "event"} Page to app A step of the task. Nothing to answer
{"t": "outcome", "outcome", "errorCode"} Page to app The task ended. See How a task ends
{"t": "start", "projectId"} App to page Runs another task on the page, for example after submitted
{"t": "close"} App to page Ends the task on screen. The page posts closed

The boot values:

Field Value
appKey The SDK's appKey
publisherUserId Your app user id
projectId The project_id of the project the user picked
apiBase ContributionHosts.apiBase
widgetOrigin ContributionHosts.widgetOrigin
mediaOrigin ContributionHosts.mediaOrigin
sdkVersion sdkVersion

The four calls:

method args value to answer
ready None null, once the SDK is started
attest None {"verdict": "passed"}: the rawValue of attest().verdict
signRequest The claims to sign, with event_type The string that signRequest(eventType: event_type, claims:) returns, or null
signContribution item_id and artifact_hash {"tuple": {"h_proof": "<proof>"}}, from signRequest(eventType: "contribution", claims:, scored: true)

Sign the claims as the page sends them, without event_type, which goes in eventType. When the claims carry platform and sdk_version, set them to ios and sdkVersion. Add no claim: DEA refuses a request with a claim the route does not take.

When signRequest returns nil for signContribution, answer {"reason": "<lastRequestRefusal>", "outcome": "refused"}. When lastRequestRefusal contains -33, the session is not sufficient yet: add "code": -33. The page then asks the user to take a moment with the task and shows it again.

attest() and signRequest() block: answer the calls off the main thread.

5. Run another task, or close

The page posts one outcome for each task. After submitted, deliver {"t": "start", "projectId": "<the same project>"} to show another task on the same page. Use the same project for every task until the user leaves the screen. After no_task, the project has nothing left for this user: show the project list again.

Example

A task screen

This view controller loads the page, answers it and reports the outcome. Create it with the user's app user id and the project_id the user picked:

import DeaBase
import DeaSDK
import UIKit
import WebKit

/// One AI data task.
final class TaskViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate {
    /// Called once, with the outcome and its errorCode.
    var onOutcome: ((String, String?) -> Void)?

    private let userId: String
    private let projectId: String
    private let key = UUID().uuidString + "|" // only the page's own script has it
    private var web: WKWebView!

    init(userId: String, projectId: String) {
        self.userId = userId
        self.projectId = projectId
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }

    override func viewDidLoad() {
        super.viewDidLoad()
        // The bridge, in the page only, before its own script runs.
        let content = WKUserContentController()
        content.addUserScript(WKUserScript(
            source: "window.deaHost = { post: function (m) { "
                + "window.webkit.messageHandlers.deaHost.postMessage('\(key)' + m); } };",
            injectionTime: .atDocumentStart,
            forMainFrameOnly: true))
        content.add(WeakHandler(self), name: "deaHost")

        let configuration = WKWebViewConfiguration()
        configuration.userContentController = content
        web = WKWebView(frame: view.bounds, configuration: configuration)
        web.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        web.navigationDelegate = self
        view.addSubview(web)

        // The page, with the API origin as its base URL.
        web.loadHTMLString(ContributionPage.html, baseURL: URL(string: ContributionHosts.apiBase))
    }

    /// Page to app.
    func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
        guard message.frameInfo.isMainFrame, // the page itself, never the task's frame
              let raw = message.body as? String, raw.hasPrefix(key), // not the page without the key
              let msg = (try? JSONSerialization.jsonObject(with: Data(raw.dropFirst(key.count).utf8)))
                  as? [String: Any]
        else { return }

        switch msg["t"] as? String {
        case "ready":
            deliver(boot())
        case "call":
            guard let id = msg["id"] as? Int, let method = msg["method"] as? String else { return }
            let args = msg["args"] as? [String: Any]
            DispatchQueue.global(qos: .userInitiated).async {
                let reply = Self.answer(id: id, method: method, args: args)
                DispatchQueue.main.async { [weak self] in self?.deliver(reply) }
            }
        case "outcome":
            onOutcome?(msg["outcome"] as? String ?? "error", msg["errorCode"] as? String)
            onOutcome = nil
        default:
            break
        }
    }

    private func boot() -> [String: Any] {
        [
            "t": "boot",
            "appKey": Dea.sdk?.appKey ?? NSNull(),
            "publisherUserId": userId,
            "projectId": projectId,
            "apiBase": ContributionHosts.apiBase,
            "widgetOrigin": ContributionHosts.widgetOrigin,
            "mediaOrigin": ContributionHosts.mediaOrigin,
            "sdkVersion": sdkVersion,
        ]
    }

    /// The four calls. Runs off the main thread: attest() and signRequest() block.
    nonisolated private static func answer(id: Int, method: String, args: [String: Any]?) -> [String: Any] {
        guard let dea = Dea.sdk else {
            return ["t": "error", "id": id, "message": "the SDK is not started"]
        }
        let value: Any
        switch method {
        case "ready":
            value = NSNull()
        case "attest":
            value = ["verdict": dea.attest().verdict.rawValue]
        case "signRequest":
            let eventType = args?["event_type"] as? String ?? ""
            value = sign(dea, eventType: eventType, args: args, scored: false) ?? NSNull()
        case "signContribution":
            if let proof = sign(dea, eventType: "contribution", args: args, scored: true) {
                value = ["tuple": ["h_proof": proof]]
            } else {
                let why = dea.lastRequestRefusal ?? "nothing signed"
                var refusal: [String: Any] = ["reason": why, "outcome": "refused"]
                if why.contains("-33") { refusal["code"] = -33 } // not sufficient yet
                value = refusal
            }
        default:
            return ["t": "error", "id": id, "message": "no method \(method)"]
        }
        return ["t": "result", "id": id, "value": value]
    }

    /// Signs the claims the page sent, as sent. Only platform and sdk_version are the app's to set.
    nonisolated private static func sign(
        _ dea: DeaSdk, eventType: String, args: [String: Any]?, scored: Bool
    ) -> String? {
        var claims = args ?? [:]
        claims.removeValue(forKey: "event_type")
        if claims["platform"] != nil { claims["platform"] = "ios" }
        if claims["sdk_version"] != nil { claims["sdk_version"] = sdkVersion }
        return dea.signRequest(eventType: eventType, claims: claims, scored: scored)
    }

    /// App to page: one JSON object, as a string.
    private func deliver(_ message: [String: Any]) {
        guard let object = try? JSONSerialization.data(withJSONObject: message),
              let quoted = try? JSONSerialization.data(
                  withJSONObject: String(decoding: object, as: UTF8.self), options: .fragmentsAllowed)
        else { return }
        let json = String(decoding: quoted, as: UTF8.self)
        web.evaluateJavaScript("window.deaPage && window.deaPage.deliver(\(json));")
    }

    /// The page and the task's frame only: nothing navigates away.
    func webView(
        _ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
        decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
    ) {
        let url = action.request.url
        let page = url.map { "\($0.scheme ?? "")://\($0.host ?? "")" } == ContributionHosts.apiBase
        let local = url?.scheme == "about" || url?.scheme == "data"
        decisionHandler(page || local ? .allow : .cancel)
    }
}

/// The content controller keeps its handler: this one holds the screen weakly.
private final class WeakHandler: NSObject, WKScriptMessageHandler {
    private weak var target: WKScriptMessageHandler?

    init(_ target: WKScriptMessageHandler) { self.target = target }

    func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
        target?.userContentController(controller, didReceive: message)
    }
}

Load the projects off the main thread, show them, and present the screen with the one the user picks:

let task = TaskViewController(userId: userId, projectId: picked["project_id"] as? String ?? "")
task.onOutcome = { [weak self, weak task] outcome, _ in
    task?.dismiss(animated: true)
    if outcome == "no_task" { self?.showProjects() } // the project has nothing left: list them again
}
present(task, animated: true)

showProjects stands for your own code. In SwiftUI, wrap TaskViewController in a UIViewControllerRepresentable.

How a task ends

The page posts exactly one outcome for each task. When the task ends on one of the page's own screens (thank you, not sent, task unavailable), the outcome comes after the user taps "Back to the app".

outcome What happened
submitted DEA stored the answer
consent_declined The user tapped "Not now" on the consent screen. Nothing was recorded or sent
no_task The picked project has nothing left for this user. Show the project list again
widget_unavailable The task's widget failed its origin or hash check. Nothing was sent
not_sent The answer could not be sent: retries ran out, DEA refused it, or the session was not sufficient on three tries
not_attested Your app answered attest with a verdict other than passed, the boot message has no appKey, or signRequest answered null. The task did not start
closed Your app delivered close before the task ended
error DEA refused the task or the consent, did not answer, or the page could not start. errorCode names the reason
errorCode Why
PAGE_NO_BOOT No boot message within 30 seconds. Your app hears it only when it receives the page's messages
PAGE_NO_HOSTS The boot message has no apiBase, widgetOrigin or sdkVersion
PAGE_INSECURE The page is not in a secure context: it was loaded without ContributionHosts.apiBase as its base URL
PAGE_ERROR The page failed while it started a task
NETWORK DEA did not answer
Another value DEA's own code, such as IDENTITY_MISMATCH

The event messages come in this order: consent_required, task_shown, not_enough_signal (the same task shows again), sending, and waiting_to_send (no answer from DEA yet, retrying).

Troubleshooting

What you see Why What to do
After 30 seconds the page says "No host bridge is installed", and your app hears nothing window.deaHost is not defined when the page runs, so the page cannot post to your app Add the user script at .atDocumentStart, before you load the page
After 30 seconds the page says "The app did not start this task", and your app hears nothing Your app drops the page's messages, its outcome included Check the handler name, the key, and that the message comes from the main frame
error with PAGE_NO_BOOT Your app hears the page, but does not answer ready with the boot message Deliver the boot message on every ready
error with PAGE_INSECURE The page was loaded with no base URL or another one Load it with loadHTMLString(_:baseURL:) and ContributionHosts.apiBase
not_attested attest() did not answer .passed, appKey is nil, or signRequest returned nil (read lastRequestRefusal) See Attest and Accounts and keys
error with CLAIM_PROFILE A signed request carries a claim the route does not take, or an app user id that is empty or longer than 128 characters Sign the claims as the page sends them, and change only platform and sdk_version
error with IDENTITY_MISMATCH This device key is bound to another app user id See App user ids
not_sent soon after the user answers Your app answered signContribution with a refusal without "code": -33, or with that code three times Add "code": -33 when lastRequestRefusal contains -33, so the page shows the task again
The task ends 30 seconds after a call Your app did not answer that call Answer every call with a result or an error message

API

Member Returns Description
ContributionPage.html String The task page
ContributionHosts.apiBase String DEA's API origin: the page's base URL, and the host of the project list. In DeaBase
ContributionHosts.widgetOrigin String The origin of the task's widget. Boot value widgetOrigin. In DeaBase
ContributionHosts.mediaOrigin String The origin of the task's images. Boot value mediaOrigin. In DeaBase
signRequest(eventType:claims:scored:sessionId:) String? Signs a task request with the device key; nil when nothing was signed. scored: true adds the session's score. Blocking
lastRequestRefusal String? Why the last signRequest returned nil
attest() Attestation Registers the device key. Blocking. See Attest
appKey String? Boot value appKey, and the X-App-Key header of the project list
sdkVersion String Boot value sdkVersion, and the sdk_version claim