Chartsv26.10.18

iOS applications

Embedding Unifin Charts into iOS apps through a WKWebView - the page setup, the Swift host, the bridge protocol and the limits to know about.

This page covers embedding the library into an iOS app through a WKWebView: the page setup, the Swift host, the bridge protocol and the limits to know about.

Unifin Charts is a browser library: it renders on a canvas through standard web APIs, so a WKWebView runs it exactly like Safari on the same OS version. No SDK and no network access are required.

How embedding works today

  1. Ship the page with your app bundle, or serve it from your backend.
  2. Load it in a WKWebView with JavaScript enabled and read access limited to the asset folder.
  3. Size the view to the chart area; the renderer adapts to any container size.
  4. Push data in through window.UnifinHost and read the cursor hook back through a message handler.
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences.allowsContentJavaScript = true

let webView = WKWebView(frame: .zero, configuration: configuration)
webView.scrollView.contentInsetAdjustmentBehavior = .never
webView.loadFileURL(pageURL, allowingReadAccessTo: assetDirectoryURL)

The page itself is platform neutral: the same index.html and app.js that the Android page documents run here unchanged.

The bridge protocol

CallDirectionWhat it does
window.UnifinHost.setBars(json)native to pageParses a bar array, filters malformed entries and repaints; returns the accepted bar count
window.UnifinHost.setTheme('dark' | 'light')native to pageSwitches the palette without rebuilding the chart
window.UnifinHost.setSymbol(symbol, timeframe)native to pageUpdates the watermark, axis labels and accessible name
window.UnifinHost.onCrosshair(handler)page to nativeRegisters the cursor readout hook
window.onUnifinBridgeEvent(kind, detail)page to nativeState changes, including ready

Android reaches the page-side function through addJavascriptInterface. On iOS the host injects a one-line bootstrap script at document start and forwards the events into a WKScriptMessageHandler:

configuration.userContentController.add(bridge, name: "unifinBridge")
configuration.userContentController.addUserScript(
    WKUserScript(
        source: """
        window.onUnifinBridgeEvent = function (kind, detail) {
          window.webkit.messageHandlers.unifinBridge.postMessage({ kind: kind, detail: detail || {} });
        };
        """,
        injectionTime: .atDocumentStart,
        forMainFrameOnly: true
    )
)

Sending data uses the same two calls as the Android host:

webView.evaluateJavaScript("window.UnifinHost.setBars(\(jsonLiteral))")
webView.evaluateJavaScript("window.UnifinHost.setTheme(\"light\")")

Note evaluateJavaScript runs on the main thread. Keep the host methods on the main queue and the JSON payload free of non-finite numbers - the page drops bars that fail validation instead of blanking the chart.

Host script

The repository ships the Swift host next to the Android harness:

PieceWhat it does
examples/ios-webview/ios/ChartBridge.swiftWKWebView host: loads the bundled page, injects the bootstrap hook, drives setBars/setTheme/setSymbol and publishes the cursor readout
examples/ios-webview/README.mdWiring steps, the shared page assets and the verified scope
examples/android-webview/*The page and the build step both platforms use

What to check on device

AreaRecommendation
TouchThe element handles pointer input; verify pan, zoom and crosshair with on-device gestures
Safe areaSet contentInsetAdjustmentBehavior = .never and inset the container yourself, so the axis never slides under the home indicator
FontsBundle fonts with the page assets - the chart reads them through the same CSS stack
PerformanceTest frame timing on the oldest supported iOS version and on the smallest target device
BackgroundPause your feed when the scene goes to the background; the page keeps painting only when it is visible
OfflineKeep data fetching in the native layer and feed bars through the bridge

Limits to know

  • The chart page must stay on bundled assets or on a host you control. Never load a remote page that can post messages into the same handler.
  • Do not enable allowsBackForwardNavigationGestures on a chart page: a swipe navigates away and drops the data set.
  • The page has no session of its own: authenticate in the native layer and pass data through the bridge, exactly as the Android host does.
  • The Swift host is a documented starting point, not a compiled target: the pipeline has no macOS runner. Its protocol is the one the page and the Android harness tests verify.

See also

On this page