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 aWKWebView and your native code.
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
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
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
pendingRequests
respond(to:status:data:error:). When a response is sent for a pending request, it is removed from this list.
capabilities
supported status. Derived from the BridgeConfiguration at initialization.
lastError
clearError() to reset.
Typed Capability Slots
documentCapture
camera.document). Set handler to declare support. Routes requests for the "camera.document.capture" action.
selfieCapture
camera.selfie). Set handler to declare support. Routes requests for the "camera.selfie.capture" action.
Properties
delegate
configuration
Methods
register(handler:)
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:)
pendingRequests instead.
registerCustomCapability(_:version:handler:)
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:)
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()
lastError to nil.
send(event:data:)
Example:
lastError if the WebView is not attached or if JSON encoding fails.
respond(to:status:data:error:)
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:)
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-connectedWKWebView.
Initializer
Example:
Properties
url
host
lastError, receivedMessages).
Coordinator
BridgeWebView.Coordinator for custom navigation handling.
BridgeWebViewConfigurator
A utility for configuring aWKWebView 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.
Static Methods
configure(_:host:)
WKWebView with the bridge:
- Injects the bootstrap user script at document start.
- Registers the
BridgeHostas the handler for the"gbgBridge"script message channel. - Attaches the WebView to the host.
Example:
makeWebView(host:)
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 ahandler declares support; the SDK handles routing, result encoding, and busy rejection automatically.
BridgeCapabilityInfo dictionaries, encode capture results into JSONValue, and keep capability declarations in sync with handler registrations. Setting a handler is the declaration.
Initializer
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()
BridgeCapabilityInfo reflecting the slot’s current state. Used internally to build capability.query responses.
awaitCompletion()
complete(_:) is called. Use this in handlers that drive SwiftUI-presented camera UI rather than imperative capture APIs.
Example:
complete(_:)
CaptureResult
A strongly-typed result returned by capture handlers.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.permissionState on capture slots without writing AVFoundation boilerplate.
Static Methods
check()
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.BridgeHost uses to initialize capability state and respond to capability queries from the web journey.
Initializer
Properties
BridgeCapabilityInfo
Metadata about a single capability.Initializer
Properties
Message models
Every value that crosses the bridge is wrapped in aBridgeMessage 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.Identifiable conformance enables use in SwiftUI lists.
Initializer
Properties
BridgePayload
The payload carried within aBridgeMessage.
Initializer
Properties
BridgeErrorPayload
Structured error information included in error responses.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.JSONValue provides a recursive enum that maps directly to JSON types, enabling type-safe construction and pattern matching of arbitrary payloads.
Cases
Properties
anyValue
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.Requirements
action
"camera.document.capture", "nfc.read"). Must be unique per BridgeHost — registering a handler with the same action replaces the previous one.
handle(request:responder:)
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.BridgeHost internals. Handlers don’t need to know about WebViews or JavaScript evaluation — they simply call respond().
Requirements
respond(status:data:error:)
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.Methods
bridgeHost(_:didReceive:)
bridgeHost(_:unhandledRequest:)
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.
BridgeHost so the web journey can always discover available capabilities.
Action: "capability.query"
Initializers
Simple Provider
init(configuration:).
Rich Provider
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 acapability.query request, the response data contains: