Skip to main content
Complete reference for every public type, method, and property in the GBGBridge framework. Module: GBGBridge Platforms: iOS 15.0+ Swift: 5.9+

Table of contents


Primary entry points

These are the types you’ll interact with directly to wire the bridge into your app: a host that routes messages, a SwiftUI view that hosts the WebView, and a configurator for UIKit or custom WebView setups.

BridgeHost

The central coordinator that manages message routing between a WKWebView and your native code.
Why it exists: BridgeHost is the main object you interact with. It decodes incoming messages from the WebView, routes requests to registered handlers, tracks pending requests, and sends responses and events back to the web journey. Threading: @MainActor — all access must be from the main thread. This is enforced by the Swift concurrency system. In SwiftUI, use @StateObject or @ObservedObject to hold a reference.

Initializers

BridgeHost offers two initializers. Most apps should use init(hostVersion:), which wires up typed capability slots automatically. Use init(configuration:) only when you need to declare capabilities explicitly via a dictionary.
init(hostVersion:) — Recommended
Creates a new bridge host with typed capability slots. Capability support is declared by setting handlers on the documentCapture and selfieCapture slots. The CapabilityQueryHandler is registered automatically with a rich provider that builds the response dynamically from typed slots and custom capabilities, including permissionState metadata. Example:

init(configuration:) — Configuration-Based
Creates a new bridge host with explicit configuration. Capabilities are declared statically in the BridgeConfiguration dictionary. Automatically registers a built-in CapabilityQueryHandler that responds to "capability.query" requests. Typed slots exist but are not wired into the query handler — use register(handler:) to add capability handlers. Example:

Published Properties

These properties are @Published and can be observed in SwiftUI views or via Combine subscribers.
receivedMessages
An ordered list of all messages received from the web journey (requests, responses, and events). Messages are appended in the order they arrive. Useful for debugging or building a message log UI.
pendingRequests
Requests from the web journey that have no registered handler. These are waiting for manual response via respond(to:status:data:error:). When a response is sent for a pending request, it is removed from this list.
capabilities
A simplified view of the declared capabilities, mapping capability identifiers to their supported status. Derived from the BridgeConfiguration at initialization.
lastError
The most recent error message, if any. Set when message decoding fails, JavaScript evaluation fails, or the WebView is not attached. Call clearError() to reset.

Typed Capability Slots

documentCapture
The typed slot for document capture (camera.document). Set handler to declare support. Routes requests for the "camera.document.capture" action.
selfieCapture
The typed slot for selfie capture (camera.selfie). Set handler to declare support. Routes requests for the "camera.selfie.capture" action.

Properties

delegate
An optional delegate that receives notifications about all incoming messages and unhandled requests. Set this to observe bridge activity without registering handlers.
configuration
The configuration passed at initialization. Read-only after creation.

Methods

register(handler:)
Registers a capability handler. When a request arrives with an action matching the handler’s action property, the handler’s handle(request:responder:) method is called. If a handler is already registered for the same action, it is replaced. Example:

unregister(action:)
Removes the handler registered for the given action. Subsequent requests for that action will be added to pendingRequests instead.
registerCustomCapability(_:version:handler:)
Registers a custom capability that appears in capability.query responses and handles requests for the given action. Use this for capabilities that don’t have a typed slot (e.g., NFC, biometrics). If a typed slot is registered for the same action ID, the typed slot takes precedence in both query responses and request routing. Example:

attach(webView:)
Associates a WKWebView with this host. Messages sent via send(event:data:) and respond(to:...) are delivered to this WebView. You do not need to call this method if you use BridgeWebView or BridgeWebViewConfigurator — they call it automatically.
The host holds a weak reference to the WebView. If the WebView is deallocated, sending messages will set lastError.

clearError()
Resets lastError to nil.
send(event:data:)
Sends an event message to the web journey. Events are fire-and-forget — no response is expected. Example:
Error cases: Sets lastError if the WebView is not attached or if JSON encoding fails.
respond(to:status:data:error:)
Sends a response to a pending request. The correlationId must match a message in pendingRequests. The matched request is removed from pendingRequests upon sending. The response’s action is automatically set to the original request’s action. Example:

respond(to:action:status:data:error:)
Sends a response with an explicit action. This overload does not look up pendingRequests — it sends directly. Use this from within a BridgeCapabilityHandler via the BridgeResponder, or when you need to respond to a request that may not be in the pending list.
userContentController(_:didReceive:)
WKScriptMessageHandler conformance. Called by WebKit when the web journey sends a message via window.webkit.messageHandlers.gbgBridge.postMessage(). You should not call this method directly.

BridgeWebView

A SwiftUI view that displays a web journey inside a bridge-connected WKWebView.
Why it exists: Provides the simplest integration path for SwiftUI apps. Handles WebView creation, configuration, bootstrap script injection, message handler registration, and URL loading.

Initializer

Example:

Properties

url
The journey URL. If this value changes, the WebView navigates to the new URL (unless the normalized URL is unchanged).
host
The bridge host. Observed so that SwiftUI can react to state changes (e.g., lastError, receivedMessages).

Coordinator

The WebView’s navigation delegate. Currently provides default behavior. You can subclass BridgeWebView.Coordinator for custom navigation handling.

BridgeWebViewConfigurator

A utility for configuring a WKWebView with the bridge infrastructure. Use this when you need more control than BridgeWebView provides — for example, in UIKit-based apps or when you need a custom WebView configuration.
Why it exists: Separates WebView setup from display. You can configure an existing WebView or create a new one with all bridge wiring in place.

Static Methods

configure(_:host:)
Configures an existing WKWebView with the bridge:
  1. Injects the bootstrap user script at document start.
  2. Registers the BridgeHost as the handler for the "gbgBridge" script message channel.
  3. Attaches the WebView to the host.
Example:

makeWebView(host:)
Creates and returns a new WKWebView that is fully configured with the bridge. Equivalent to creating a WKWebView and calling configure(_:host:). Returns: A configured WKWebView instance.

Capabilities

CaptureCapability

A typed capability slot that represents a capture operation (document or selfie). Setting a handler declares support; the SDK handles routing, result encoding, and busy rejection automatically.
Why it exists: Eliminates the need to manually build BridgeCapabilityInfo dictionaries, encode capture results into JSONValue, and keep capability declarations in sync with handler registrations. Setting a handler is the declaration.

Initializer

You typically don’t create CaptureCapability instances directly — use the built-in slots on BridgeHost (documentCapture, selfieCapture).

Properties

Methods

These methods drive capability handling at runtime — building query responses, awaiting capture completion, and signalling cancellation:
buildCapabilityInfo()
Returns a BridgeCapabilityInfo reflecting the slot’s current state. Used internally to build capability.query responses.
awaitCompletion()
Suspends the current handler until complete(_:) is called. Use this in handlers that drive SwiftUI-presented camera UI rather than imperative capture APIs. Example:

complete(_:)
Resumes the pending handler with a capture result. Call from view-layer code (e.g., camera callback closures) to complete the flow. Example:

CaptureResult

A strongly-typed result returned by capture handlers.
Why it exists: Eliminates manual JSONValue dictionary construction. The SDK converts CaptureResult values to the bridge protocol format automatically.

Cases


DocumentCaptureResult

Result data for a successful document capture.

Initializer

Bridge response data:

SelfieCaptureResult

Result data for a successful selfie capture.

Initializer

Bridge response data:

PermissionState

The current authorization status for a native capability.

CameraDetector

A utility for detecting camera hardware availability and permission status.
Why it exists: Provides a simple way to populate permissionState on capture slots without writing AVFoundation boilerplate.

Static Methods

check()
Checks camera hardware availability using AVCaptureDevice.default(for: .video) and permission status using AVCaptureDevice.authorizationStatus(for: .video). Returns: A CameraDetector.Result with hardware and permission info.

CameraDetector.Result

Example:

Configuration

BridgeConfiguration

Declares the host application’s version and supported capabilities.
Why it exists: Provides a single configuration object that BridgeHost uses to initialize capability state and respond to capability queries from the web journey.

Initializer

Properties


BridgeCapabilityInfo

Metadata about a single capability.
Why it exists: Allows the host to express not just whether a capability is supported, but also its version and any constraints (e.g., maximum resolution, supported document types).

Initializer

Properties


Message models

Every value that crosses the bridge is wrapped in a BridgeMessage envelope, which carries a typed payload, a correlation ID, and a status. The types in this section describe that envelope and the shapes you’ll embed inside it.

BridgeMessage

A structured envelope for all bridge communication.
Why it exists: Provides a consistent, type-safe format for all messages exchanged between the web journey and the native host. The Identifiable conformance enables use in SwiftUI lists.

Initializer

Properties


BridgePayload

The payload carried within a BridgeMessage.

Initializer

Properties


BridgeErrorPayload

Structured error information included in error responses.
Why it exists: Provides machine-readable error codes alongside human-readable messages, plus a recoverable flag that tells the web journey whether it should retry or fail.

Initializer

Properties


BridgeMessageType

The type of a bridge message.

BridgeResponseStatus

The status of a response message.

JSONValue

A type-safe representation of arbitrary JSON values.
Why it exists: Swift’s type system doesn’t natively represent heterogeneous JSON. JSONValue provides a recursive enum that maps directly to JSON types, enabling type-safe construction and pattern matching of arbitrary payloads.

Cases

Properties

anyValue
Converts the JSONValue to its Foundation equivalent (String, Double, Bool, [String: Any], [Any], or NSNull). Useful for interoperating with APIs that expect Any.

Codable Conformance

JSONValue automatically decodes from and encodes to standard JSON. The decoding order is: null → bool → number → string → object → array. Example — constructing a payload:

Protocols

BridgeCapabilityHandler

The interface for objects that handle specific bridge request actions.
Why it exists: Defines the contract for capability implementations. Each handler is responsible for a single action and receives a responder to send its result back to the web journey.

Requirements

action
The action identifier this handler responds to (e.g., "camera.document.capture", "nfc.read"). Must be unique per BridgeHost — registering a handler with the same action replaces the previous one.
handle(request:responder:)
Called when a request arrives with a matching action. Perform your native operation and call responder.respond(...) when done. Threading: This method is async and runs in a Task dispatched by BridgeHost. You can safely await async operations, present UI (from the main actor), and perform background work. Example:

BridgeResponder

A callback interface used to send a response from a capability handler back to the web journey.
Why it exists: Decouples the handler from BridgeHost internals. Handlers don’t need to know about WebViews or JavaScript evaluation — they simply call respond().

Requirements

respond(status:data:error:)
Sends a response to the web journey for the associated request. Threading: Safe to call from any thread. The internal implementation dispatches to the main actor.
Call this method exactly once per request. Calling it multiple times has no effect (the first call wins for request correlation).

BridgeHostDelegate

An observer protocol for monitoring bridge activity.
Why it exists: Provides a way to observe all bridge messages and react to unhandled requests without registering a handler. Useful for logging, analytics, or building custom request handling logic.

Methods

bridgeHost(_:didReceive:)
Called for every message received from the web journey, regardless of type. Default implementation does nothing.
bridgeHost(_:unhandledRequest:)
Called when a request arrives with no registered handler. The request is also added to host.pendingRequests. Default implementation does nothing.

Built-in handlers

CapabilityQueryHandler

A built-in handler that responds to "capability.query" requests with the host’s declared capabilities.
Why it exists: Capability negotiation is fundamental to the bridge protocol. This handler is automatically registered by BridgeHost so the web journey can always discover available capabilities. Action: "capability.query"

Initializers

Simple Provider
Creates a query handler with a simple boolean capability map. Used by init(configuration:).
Rich Provider
Creates a query handler with full capability metadata including permissionState. Used by init(hostVersion:).
You rarely need to create either initializer directly. BridgeHost creates and registers the appropriate one automatically.

Response Format

When the web journey sends a capability.query request, the response data contains: