Dari
iOS

Capture bridge calls

Record iOS bridge traffic with the interceptor, autoCapture or DariMacros

Record bridge calls in one of three ways. Start Dari first, as in Getting started.

Choose a capture method

All three show the same thing in the desktop app, so pick by how you want the recording to get into your code:

InterceptorautoCaptureDariMacros
How it recordsYou call interceptor in your bridge codeSwaps WebKit methods at runtime (method swizzling)A macro writes the recording call into your handler at compile time
What you changeEvery send and receiveOne line in start()One attribute per handler type, and dari* instead of evaluateJavaScript
Covers third-party SDK handlersNoYesNo

Choose DariMacros when your team avoids swizzling, another SDK already swizzles WebKit, or you want to see in code exactly which handlers are recorded. Otherwise autoCapture is less work.

Record bridge calls

Create one interceptor per WKWebView, then call it where your bridge receives and answers messages. The methods match Android's DariInterceptor.

final class Bridge: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
    private let dari = Dari.shared.interceptor(tag: "main")
    weak var webView: WKWebView?

    // Requests recorded afterwards carry this page URL, without its query or fragment.
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        dari.onPageUrlChanged(webView.url?.absoluteString)
    }

    // Web → App
    func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
        let body = message.body as? [String: Any] ?? [:]
        let handler = body["handler"] as? String ?? message.name
        let requestId = body["requestId"] as? String
        dari.onWebToAppRequest(handlerName: handler, requestId: requestId, requestData: body["data"] as? String)

        let result = #"{"ok":true}"#
        dari.onWebToAppResponse(handlerName: handler, requestId: requestId, responseData: result, isSuccess: true)
        // ...send the result back to the page
    }

    // App → Web
    func notifyPage(_ requestId: String, _ payload: String) {
        dari.onAppToWebRequest(handlerName: "onResume", requestId: requestId, data: payload)
        webView?.evaluateJavaScript("onResume(\(payload))") { value, error in
            self.dari.onAppToWebResponse(requestId: requestId, isSuccess: error == nil, responseData: value.map { "\($0)" })
        }
    }
}
  • Requests and responses are paired by requestId. A response completes the newest open request with the same ID, tag, and direction.
  • fireAndForget: true records a message that is complete as soon as it is sent. A nil requestId alone only skips pairing: the message stays in progress unless fireAndForget (per call or in DariConfiguration) is true.
  • Pass displayName: when the handler name isn't readable on its own.
  • Calls made before start() are ignored.
  • For protobuf bytes, use the …Protobuf… methods. See Protocol Buffers.

Automatic capture

Since 3.1.0, Dari can record bridge traffic without interceptor calls, like the Android Gradle plugin. Pass autoCapture to start(), before your app creates its web views:

try Dari.shared.start(DariConfiguration(autoCapture: DariAutoCapture(tag: "main")))

Dari then hooks WebKit at runtime:

WebKit callRecorded as
A handler added with add(_:name:) receives a messageWeb → App request
A WKScriptMessageHandlerWithReply repliesThe response to that request
evaluateJavaScriptApp → Web request, answered by its completion result or error

Each WKWebView gets its own interceptor, and the page URL is read from the web view on every call.

By default, a dictionary body's handler, requestId and data fields name and pair the call, and a script is named after the function it calls. When your bridge uses other fields, or answers the page through a callback script, map them yourself:

DariAutoCapture(
    tag: "main",
    parseMessage: { name, body in
        let fields = body as? [String: Any] ?? [:]
        if fields["type"] as? String == "appToWebResponse" {
            return .response(requestId: fields["requestId"] as? String ?? "", data: fields["data"] as? String, isSuccess: fields["success"] as? Bool ?? false)
        }
        return DariAutoCapture.defaultMessage(name: name, body: body)
    },
    parseScript: { script in
        // onBridgeResponse("<id>", true, "<json>") answers a Web → App request.
        guard script.hasPrefix("onBridgeResponse(") else { return DariAutoCapture.defaultScript(script) }
        return .response(requestId: parseRequestId(script), data: script, isSuccess: !script.contains(", false,"))
    }
)
  • A .request with a requestId waits for a response carrying that ID. Without one, Dari generates an ID and pairs the call with its reply or completion.
  • Return .ignore for traffic you don't want to see.
  • Handlers added before start(), and Swift bridge code outside these WebKit calls, aren't captured. Use the interceptor for those.
  • Leave autoCapture off if your bridge already calls the interceptor, or messages are recorded twice.

Compile-time capture with macros

Since 3.2.0, Dari offers a third way to record bridge traffic: a Swift macro that adds the recording call to your handler while it compiles. See Choose a capture method for how it compares.

New to Swift macros? A macro is code that runs inside the compiler and adds code to yours. The result isn't a separate generated file: it is merged into the declaration you put the attribute on. In Xcode, right-click the attribute and choose Expand Macro to see the generated code.

1. Add the DariMacros library

In Xcode, open your target's General → Frameworks, Libraries, and Embedded Content, click +, and add DariMacros from the dari package. It includes Dari, so import DariMacros is enough. With Package.swift:

.product(name: "DariMacros", package: "dari")

The first build asks you to trust the macro: choose Trust & Enable. On CI, pass -skipMacroValidation to xcodebuild. Macros need Xcode 16 or later, which every current Xcode is.

2. Mark your message handler

Put @DariBridge on the class that implements WKScriptMessageHandler, the one you register with add(_:name:):

import DariMacros

@DariBridge(tag: "main")
final class Bridge: NSObject, WKScriptMessageHandler, WKScriptMessageHandlerWithReply {
    func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
        // your code, unchanged
    }

    func userContentController(
        _ controller: WKUserContentController,
        didReceive message: WKScriptMessage,
        replyHandler: @escaping (Any?, String?) -> Void
    ) {
        // your code, unchanged
    }
}

That's all for the Web → App side. The macro finds each message handler method and adds one line at the top of it. Conceptually the second method becomes:

func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage, replyHandler: @escaping (Any?, String?) -> Void) {
    let replyHandler = _DariBridgeSupport.record(message, tag: "main", replyHandler: replyHandler)
    // your code, unchanged
}

The message is recorded as a Web → App request, and the wrapped replyHandler records your answer as its response. You never call _DariBridgeSupport yourself.

  • Covered methods: userContentController(_:didReceive:), userContentController(_:didReceive:replyHandler:), and the async -> (Any?, String?) form. Other methods in the type are left alone.
  • tag and parseMessage work as in DariAutoCapture.
  • Handlers in an extension need @DariBridge on that extension too, because a macro only sees the declaration it is attached to:
@DariBridge(tag: "main")
extension Bridge: WKScriptMessageHandlerWithReply {
    func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) async -> (Any?, String?) { … }
}

3. Call the dari versions of the WebKit script calls

App → Web calls happen wherever you call them, not inside the handler, and a macro can only change the declaration it's attached to. So for these calls, use the dari versions, which run the same WebKit call and record it:

Instead ofCall
evaluateJavaScript(_:completionHandler:)dariEvaluateJavaScript(_:tag:completionHandler:)
evaluateJavaScript(_:in:in:completionHandler:)dariEvaluateJavaScript(_:in:in:tag:completionHandler:)
callAsyncJavaScript(_:arguments:in:in:completionHandler:)dariCallAsyncJavaScript(_:arguments:in:in:tag:completionHandler:)

Each has an async form too:

webView.dariEvaluateJavaScript("onPush(\(json))", tag: "main") { result, error in … }
let title = try await webView.dariEvaluateJavaScript("document.title", tag: "main")

They take the same parseScript as DariAutoCapture; dariCallAsyncJavaScript passes it the function body.

Good to know

  • The macro runs on your Mac while compiling, so swift-syntax isn't linked into your app. SPM still downloads it when resolving the package, even for apps that link only Dari.
  • Recording does nothing until start(), so builds that never start Dari record nothing.
  • Bridge handlers inside third-party SDKs can't carry the macro. Turn on autoCapture for those.
  • You can use both: with autoCapture on as well, each message is recorded once, under the autoCapture tag.
  • Throwing handlers aren't supported, because WebKit's message handler methods don't throw.
  • Declare parseMessage outside the type the macro is on. @DariBridge(parseMessage: MyBridge.parse) on MyBridge fails with "circular reference resolving attached macro", so keep the parser in a separate enum or as a global.

On this page