Skip to content

Apple Native Layer (Swift and Swift Package Manager)

The Apple native layer is where ZikZak InAppWebView stops being Dart and becomes WebKit. Two federated plugin packages — zikzak_inappwebview_ios and zikzak_inappwebview_macos — wrap the platform WKWebView (UIKit on iOS, AppKit on macOS), expose it to Flutter as a platform view, and bridge every controller call over method channels. Both packages ship as Swift Package Manager manifests consumed by Flutter’s FlutterGeneratedPluginSwiftPackage, not as CocoaPods. This page is a code-archaeology walkthrough of that layer for engineers who need to modify native behavior, add a channel method, or reason about cross-platform parity. The central architectural insight is that the two packages are deliberately near-mirrors: identical channel names, identical persistentUUID derivation, identical headless-cap semantics — but they diverge in three structural places (entry-point wiring, the macOS Objective-C exception boundary, and the iOS-only security/storyboard resources), and those divergences are the parts worth understanding first.

Each Apple package is a SwiftPM manifest that declares a single library product, depends on a local FlutterFramework shim, and floors at a specific OS version. The iOS manifest additionally pulls in OrderedSet and bundles two resource types; the macOS manifest declares a second Swift target purely to host an Objective-C exception catcher. The Dart side binds each package through dartPluginClass identifiers declared in the package pubspec.yaml, which is the seam that lets the federated plugin machinery route platform calls to the right native pluginClass.

Dimension iOS package macOS package
Swift tools version 5.9 5.9
Platform floor .iOS("15.0") .macOS("12.0")
External dependency OrderedSet (>= 6.0.3) none
Extra native target — ZikzakExceptionCatcher (ObjC)
Bundled resources PrivacyInfo.xcprivacy, Storyboards none declared
pluginClass InAppWebViewFlutterPlugin InAppWebViewFlutterPlugin
dartPluginClass IOSInAppWebViewPlatform MacOSInAppWebViewPlatform

The iOS floor of 15.0 is intentional and load-bearing: every iOS 15.4/16/16.4/17+ API in the sources is individually availability-guarded so that apps targeting iOS 15.0 still compile (the regression that produced issue #316). The macOS floor of 12.0 plays the same role for macOS 14.0 proxy and macOS 13+ registration APIs.

Sources: Package.swift, Package.swift, pubspec.yaml, pubspec.yaml

Plugin Registration and the Manager Object Graph

Section titled “Plugin Registration and the Manager Object Graph”

The two entry points reveal the deepest structural divergence in the layer. On iOS, InAppWebViewFlutterPlugin.register immediately delegates to SwiftFlutterPlugin, a single god-object that owns every manager as a stored property and registers the platform-view factory. On macOS, InAppWebViewFlutterPlugin is the owner: it builds a method channel, registers InAppWebViewFactory, and instantiates managers directly, taking a registrar rather than a plugin reference. This is why iOS managers reach the world through plugin.registrar! while macOS managers receive registrar at construction — the dependency flows in opposite directions.

graph TD
subgraph iOS
A1[InAppWebViewFlutterPlugin.register] --> A2[SwiftFlutterPlugin.init]
A2 --> A3[FlutterWebViewFactory registered]
A2 --> A4[InAppWebViewManager]
A2 --> A5[HeadlessInAppWebViewManager]
A2 --> A6[MyCookieManager / MyWebStorageManager]
A2 --> A7[ProxyManager iOS 17 guard]
A2 --> A8[Passkey / PrintJob / CredentialDatabase]
end
subgraph macOS
B1[InAppWebViewFlutterPlugin.register] --> B2[MethodChannel dev.zuzu/zikzak_inappwebview]
B1 --> B3[InAppWebViewFactory registered]
B1 --> B4[HeadlessInAppWebViewManager registrar]
B1 --> B5[MyCookieManager + headlessManager link]
B1 --> B6[ProxyManager macOS 14 guard]
end

The iOS SwiftFlutterPlugin.init is the canonical object graph: it registers the FlutterWebViewFactory under VIEW_TYPE_ID, then constructs platformUtil, inAppBrowserManager, headlessInAppWebViewManager, chromeSafariBrowserManager, inAppWebViewManager, credentialDatabase, and conditionally proxyManager (iOS 17+), myCookieManager (iOS 11+), myWebStorageManager (iOS 9+), webAuthenticationSessionManager, and printJobManager. Teardown is symmetric — detachFromEngine disposes and nils every manager under the same availability guards. The macOS entry point is leaner: it wires a single method channel, registers InAppWebViewFactory with the view id "dev.zuzu/zikzak_inappwebview", and crucially sets MyCookieManager.headlessManager = instance.headlessInAppWebViewManager so cookie operations can be scoped to a specific headless WebView’s data store rather than the shared default.

Sources: InAppWebViewFlutterPlugin.swift, SwiftFlutterPlugin.swift, InAppWebViewFlutterPlugin.swift

The Platform-View Pipeline: Factory, Controller, WKWebView

Section titled “The Platform-View Pipeline: Factory, Controller, WKWebView”

A Flutter InAppWebView widget is realized natively through a three-stage pipeline: a FlutterPlatformViewFactory that Flutter calls to mint a view, a FlutterWebViewController that wraps a container view, and the InAppWebView itself (a WKWebView subclass). The factory is where keep-alive, headless adoption, and popup reparenting are resolved before a fresh webview is ever built.

sequenceDiagram
participant Flutter
participant Factory as FlutterWebViewFactory
participant Ctrl as FlutterWebViewController
participant WV as InAppWebView (WKWebView)
Flutter->>Factory: create(withFrame, viewId, args)
alt headlessWebViewId present
Factory->>Factory: disposeAndGetFlutterWebView
else keepAliveId present
Factory->>Factory: reuse keepAliveWebViews[id]
else windowId present (popup)
Factory->>Factory: adopt windowWebViews[windowId]
else fresh
Factory->>Ctrl: new(plugin, frame, viewId, params)
Ctrl->>WV: InAppWebView(config, contextMenu, userScripts)
Ctrl->>Ctrl: attach PullToRefresh + FindInteraction
end
Factory-->>Flutter: FlutterPlatformView
Factory->>Ctrl: makeInitialLoad(params)

On iOS the resolution order inside FlutterWebViewFactory.create is precise: adopt a headless webview if headlessWebViewId matches, else reuse a keep-alive controller, else build a new FlutterWebViewController; shouldMakeInitialLoad is true only when no existing webview was adopted, which prevents double navigation on hot-restart recovery. The FlutterWebViewController initializer parses initialSettings into InAppWebViewSettings, builds a preWKWebViewConfiguration, and — when a windowId is supplied — reuses the popup WKWebView transport and rebinds a fresh WebViewChannelDelegate to the new view id. The macOS InAppWebViewFactory achieves the same adoption but retains the controller via objc_setAssociatedObject on the container view, because the macOS FlutterWebViewController is a plain NSObject wrapper rather than a FlutterPlatformView.

Sources: FlutterWebViewFactory.swift, FlutterWebViewController.swift, InAppWebViewFactory.swift, FlutterWebViewController.swift

Every native capability is reached over a Flutter method channel, and the channel names form a stable contract shared across both Apple packages (and mirrored on other platforms). There are two channel granularities: per-view channels (one WebViewChannelDelegate per webview id, dispatching through the WebViewChannelDelegateMethods enum) and singleton manager channels (one per manager, registered at plugin startup). The per-view method set is large — navigation, JavaScript injection, settings, screenshots, find, media, content-blocker hooks — and is dispatched by a strict enum-backed switch that returns FlutterMethodNotImplemented for any unknown method.

Channel name Owner Granularity
wtf.zikzak/zikzak_inappwebview_<viewId> WebViewChannelDelegate per-view
wtf.zikzak/zikzak_inappwebview_manager InAppWebViewManager singleton
wtf.zikzak/flutter_headless_inappwebview HeadlessInAppWebViewManager singleton
wtf.zikzak/zikzak_inappwebview_cookiemanager MyCookieManager singleton
wtf.zikzak/zikzak_inappwebview_proxycontroller ProxyManager singleton
wtf.zikzak/zikzak_inappwebview_platformutil PlatformUtil singleton
wtf.zikzak/zikzak_inappbrowser (+ _ prefix) InAppBrowserManager / controller singleton + per-browser
dev.zuzu/zikzak_inappwebview macOS InAppWebViewFlutterPlugin singleton (macOS)

The per-view dispatcher is the highest-traffic seam in the layer. WebViewChannelDelegate.handle first attempts WebViewChannelDelegateMethods(rawValue: call.method) and bails with FlutterMethodNotImplemented if the method is unknown, then switches over the enum — getUrl, getTitle, getProgress, loadUrl, postUrl, loadData, evaluateJavascript, injectCSSCode, takeScreenshot, setSettings, and dozens more. The macOS side mirrors this with bindChannels(registrar:viewId:channelName:), which (re)binds the channel when a popup webview is reparented into a platform view.

Sources: WebViewChannelDelegate.swift, WebViewChannelDelegateMethods.swift, InAppWebViewManager.swift, InAppWebView.swift

Availability Discipline and the iOS 15.0 Floor

Section titled “Availability Discipline and the iOS 15.0 Floor”

Because the package floors at iOS 15.0 but uses APIs up to iOS 17.4, availability is enforced per-API rather than per-file. The plugin constructor guards ProxyManager behind if #available(iOS 17.0, *), MyCookieManager behind iOS 11.0, and MyWebStorageManager behind iOS 9.0; teardown repeats the identical guards with a cast-and-dispose pattern. The ProxyManager class itself is annotated @available(iOS 17.0, *) and imports the Network framework for ProxyConfiguration.

This discipline is not left to reviewer vigilance — it is encoded as an executable Dart test, swift_availability_usage_test.dart, that scans every Swift source and fails if any #available/#unavailable condition is used as a boolean operand instead of as the direct condition of an if/guard/while. That exact misuse (!hasValidPersistentId || !#available(iOS 17.0, *)) was the compile error reported in issue #316. A sibling test, storyboard_deployment_target_test.dart, enforces that WebView.storyboard’s Interface Builder <deployment version> is not older than the package’s .iOS("…") floor, decoding IB’s major*1024 + minor*64 encoding to compare.

Sources: SwiftFlutterPlugin.swift, ProxyManager.swift, swift_availability_usage_test.dart, storyboard_deployment_target_test.dart

Headless WebViews and the Live-Instance Cap

Section titled “Headless WebViews and the Live-Instance Cap”

Headless webviews are off-screen WKWebViews that own a WebContent process and navigation queue each, managed by HeadlessInAppWebViewManager over the shared wtf.zikzak/flutter_headless_inappwebview channel. Both packages impose a hard ceiling on live instances, but they resolve overflow differently — a subtle but important parity gap. The iOS manager defaults to a cap of 3 and, on overflow, recycles the least-recently-used instance (tracked via a lastUsed: [String: Date] map), because a saturated cap would otherwise permanently refuse creates after a Dart hot restart orphans native instances. The macOS manager defaults to 5 and fails loudly with a headless_cap_exceeded Flutter error, ordering by registration sequence (liveOrder) rather than recency.

Behavior iOS macOS
Default cap 3 5
Overflow policy recycle LRU instance fail with headless_cap_exceeded
Ordering key lastUsed (recency) liveOrder (registration)
Defensive id read yes (#371 R2) yes (#371 R2)

Both managers read the id argument defensively (arguments?["id"] as? String) and reject setMaxLiveWebViews values below 1 with a headless_invalid_arguments error, a hardening that prevents a shared-channel call without an id from trapping the app. The run method validates id and params before materializing an instance.

Sources: HeadlessInAppWebViewManager.swift, HeadlessInAppWebViewManager.swift

Multi-account isolation rests on a single deterministic helper, persistentUUID(from:), duplicated 1:1 across both packages. It maps a stable identifier string into a stable UUID for WKWebsiteDataStore(forIdentifier:) using a three-shape priority: (a) a direct UUID string, (b) a legacy 64-char SHA-256 hex path (first 32 hex chars become the UUID’s 16 raw bytes, preserving existing on-disk stores), or (c) a SHA-256 of the UTF-8 bytes via CryptoKit. Because all three shapes are deterministic, the same identifier always reopens the same on-disk store across relaunches — the property that makes a per-account session durable.

ProxyManager layers on top of this. On iOS it maintains profileProxies: [String: ProxyConfiguration] keyed by persistentStoreIdentifier and a weak registry of liveStores (NSHashTable<WKWebsiteDataStore>), so a per-profile proxy is applied to that profile’s data store rather than only the default. The registry key is trimmed via registryKey(_:) to match the trimming persistentUUID performs — a padded identifier and an unpadded profile id must address the same store. The macOS ProxyManager mirrors this registry (issue #410) behind a macOS 14.0 guard. A documented WebKit caveat follows: proxyConfigurations only affect processes created after the write, so an already-loading page keeps its route until its process is recreated.

Sources: InAppWebView.swift, InAppWebView.swift, ProxyManager.swift

The single most macOS-specific construct in the layer is the ZikzakExceptionCatcher target — a tiny Objective-C function ZikzakCatchException that wraps a block in @try/@catch and returns the caught NSException. It exists because Swift cannot catch NSException, and WebKit’s script-message deserialization boundary (WKScriptMessage.body) can throw one — a DOMException posted through the bridge historically caused a SIGSEGV inside CloneDeserializer::readDOMException (issue #309).

WeakScriptMessageHandler is the single registration point for every macOS script-message handler (consoleHandler, callHandler, onFindResultReceived, the web-message listeners, onScrollChangedReceived). It touches message.body exactly once inside the ObjC exception boundary via defensivelyDeserializeBody(of:), then recursively sanitizes the result with sanitizeValueForMessageCodec so that non-codec-safe leaves (NSDate, NSURL, opaque objects, foreign classes) become strings before reaching Dart. Delegates that adopt the DefensivelyDeserializedScriptMessageHandling protocol receive the pre-sanitized body; foreign delegates fall back to legacy unguarded forwarding with a logged warning. iOS has no equivalent target because the iOS WKScriptMessageHandler path does not carry this same crash class.

Sources: ZikzakExceptionCatcher.m, WeakScriptMessageHandler.swift, Package.swift

iOS-Only Capabilities: Security Coordinator, Passkeys, Storyboards

Section titled “iOS-Only Capabilities: Security Coordinator, Passkeys, Storyboards”

Three capability clusters are iOS-only in the current tree. The Security directory houses a SecurityCoordinator that composes CertificatePinningManager, HTTPSOnlyManager, and URLValidationManager behind a single validateNavigationRequest(_:) returning a SecurityDecision; it supports a global setSecurityEnabled toggle and optional audit logging. The PasskeyBridge implements WebAuthn/passkey ceremonies over ASAuthorizationController (issue #384), driven by an injected PasskeysJS shim that forwards navigator.credentials.create/get to the bridge; every call resolves with an {"ok": true, "credential": …} or {"ok": false, "error": {"name": <DOMException>}} envelope, and per-API guards cover cancel() (iOS 16), excludedCredentials (iOS 17.4), and residentKeyPreference (iOS 17.4). The macOS package ships its own PasskeyBridge (since 6.2.2) plus a NotificationBridge, but the Security coordinator and the Storyboards/.xcprivacy resources are iOS-specific — the iOS Package.swift is the only manifest that declares .process("PrivacyInfo.xcprivacy") and .process("Storyboards").

The iOS InAppBrowser is also richer: InAppBrowserManager loads InAppBrowserWebViewController and InAppBrowserNavigationController from the WebView storyboard (constant WEBVIEW_STORYBOARD = "WebView"), giving the in-app browser its native chrome (close/reload/back/forward/share buttons, search bar, progress bar). On macOS the in-app browser is window/factory-driven rather than storyboard-driven.

Sources: SecurityCoordinator.swift, PasskeyBridge.swift, InAppBrowserManager.swift, Package.swift

The iOS package additionally carries build_ios_xcframework.sh, a distribution helper that archives device and simulator slices with BUILD_LIBRARY_FOR_DISTRIBUTION=YES, combines them via xcodebuild -create-xcframework into dist/zikzak_inappwebview_ios.xcframework, and then verifies with otool -L that no obsolete /usr/lib/swift/libswift overlay dylibs are linked — failing the build if any remain. This guards against the legacy Swift-overlay breakage that modern SDKs (iOS 17/18, macOS 15, visionOS) reject. The script’s MIN_IOS_VERSION is documented to be kept in sync with the podspec. The macOS package has no analogous script; it is consumed directly as a SwiftPM package.

Sources: build_ios_xcframework.sh

The following table is the engineer’s cheat-sheet for reasoning about where the two Apple packages behave identically versus where they structurally differ. Identical rows can be changed on one side and safely mirrored to the other; divergent rows require deliberate, separate treatment.

Concern Parity Notes
Channel names identical shared cross-platform contract
persistentUUID(from:) identical 1:1 CryptoKit derivation
Headless cap semantics divergent iOS=3 LRU recycle, macOS=5 fail-loud
Entry-point ownership divergent iOS god-object SwiftFlutterPlugin; macOS self-owned plugin
Script-message safety divergent macOS ObjC exception boundary; iOS none
Proxy manager identical logic iOS 17 / macOS 14 guards
Security coordinator iOS-only no macOS equivalent
Resources (storyboard, xcprivacy) iOS-only macOS declares none
Distribution helper iOS-only build_ios_xcframework.sh

Sources: SwiftFlutterPlugin.swift, InAppWebViewFlutterPlugin.swift, HeadlessInAppWebViewManager.swift

To understand how the Dart side of these channels is declared and routed, read The Platform Interface: The Contract Seam and Domain Controller Facades: Navigation, JavaScript, Cookies, Settings. For the lifecycle that governs when these native webviews are torn down or kept alive, continue to Disposal Lifecycle and KeepAlive Patterns and Headless WebView and the Live-Instance Cap. The passkey bridge on this layer is expanded in WebAuthn and Passkey Bridge, and proxy/content-blocker behavior in Content Blockers, Proxy, and Tracing. To compare against the other native backends, see Android Native Layer (Java) and Linux WPE WebKit Backend.