Ship An Offline Help Library With SwiftUI WebKit
A help screen that needs Wi-Fi to explain a connection error has chosen an awkward moment to be ironic.
For a small set of instructions, onboarding references, or troubleshooting pages, bundling the content with the app gives the reader something useful even before the first successful network request. HTML is convenient when that content already comes from a documentation workflow.
Our SwiftUI WebView introduction covers displaying a page. This time, we’ll build a complete small library: two HTML documents, one shared stylesheet, predictable resource URLs, and explicit navigation rules.
The APIs arrived in iOS 26 and macOS 26. The examples below use Swift 6.2 or later and were checked with the installed Xcode 27 / Swift 6.4 toolchain. This is an application of established APIs, not a new October SDK announcement.
Start with the resource problem
Questions about local HTML and its linked resources have been around for years and already have answers. The useful next step is making the whole feature predictable, rather than stopping after the first page appears.
Use Your Loaf’s custom URL scheme article is a good starting point for the SwiftUI API. We’ll extend the idea with an explicit resource manifest and a separate rule for document navigation.
Apple demonstrates local-resource loading in Meet WebKit for SwiftUI. A WebPage controls the content, a WebView displays it, and a URLSchemeHandler supplies bytes for a custom scheme.
Our URLs will look like app-help://bundle/index.html. The hostname is a namespace we choose, not a server we need to run. We register this scheme on the page’s configuration below; it does not need an app-level URL Type or deep-link registration.
Give the library three real files
Create a Help folder containing the following files. Add it to the app target as a folder resource, preserving the Help directory in the built bundle. Check target membership and Copy Bundle Resources; simply seeing a file in Xcode’s navigator does not establish its bundle location.
Start with Help/index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; style-src app-help:; base-uri 'none'; form-action 'none'">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Offline Help</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Help that travels with you</h1>
<p>These instructions are included with the app.</p>
<p><a href="shortcuts.html">Read the quick tips</a></p>
<h2 id="saved-items">Saved items</h2>
<p>Use search to find an item in your saved collection.</p>
</main>
</body>
</html>
Then add Help/shortcuts.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; style-src app-help:; base-uri 'none'; form-action 'none'">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Quick Tips</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Quick tips</h1>
<ul>
<li>Choose descriptive names for saved items.</li>
<li>Use the Find button to search this help page.</li>
</ul>
<p><a href="index.html#saved-items">Back to saved items</a></p>
</main>
</body>
</html>
Both pages share Help/style.css:
:root { color-scheme: light dark; }
body {
font: -apple-system-body;
line-height: 1.6;
margin: 0;
padding: 24px;
overflow-wrap: anywhere;
}
main { max-width: 42rem; margin: 0 auto; }
a { text-underline-offset: 0.2em; }
Keep the viewport scalable. The example does not disable zoom, and its HTML uses headings, links, and a list instead of drawing the help content into an image. Test your actual content with larger text and VoiceOver before shipping.
Relative URLs do the work here. From app-help://bundle/index.html, style.css resolves to app-help://bundle/style.css, while the tips link resolves to the second document. The return link also includes a normal fragment identifier.
The early Content Security Policy meta element permits styles from our scheme and blocks other default resource sources, base-URL overrides, and form submission. The CSP specification’s meta delivery rules explain why the policy belongs before resource-loading elements. We are using it for our own bundled HTML; this example is not a renderer for arbitrary imported web content.
Load a fixed manifest away from the main actor
Put the four Swift blocks in this article in one Swift file. This first block knows which assets exist and what each asset means:
import Foundation
nonisolated struct HelpResource: Sendable {
let mimeType: String
let data: Data
}
nonisolated enum HelpError: Error, Equatable {
case invalidRequest
case unknownResource
case missingBundleFile(String)
}
nonisolated struct HelpLibrary: Sendable {
static let home = URL(string: "app-help://bundle/index.html")!
let resources: [String: HelpResource]
func resource(for request: URLRequest) throws -> HelpResource {
guard request.httpMethod == "GET",
let url = request.url,
let parts = URLComponents(url: url, resolvingAgainstBaseURL: false),
parts.scheme == "app-help", parts.host == "bundle",
parts.user == nil, parts.password == nil, parts.port == nil,
parts.query == nil
else { throw HelpError.invalidRequest }
guard let resource = resources[parts.percentEncodedPath] else {
throw HelpError.unknownResource
}
return resource
}
func allowsDocument(_ request: URLRequest) -> Bool {
(try? resource(for: request))?.mimeType == "text/html"
}
@concurrent
static func bundled(in bundle: Bundle = .main) async throws -> HelpLibrary {
let manifest = [
(name: "index", ext: "html", mime: "text/html"),
(name: "shortcuts", ext: "html", mime: "text/html"),
(name: "style", ext: "css", mime: "text/css")
]
var resources: [String: HelpResource] = [:]
for entry in manifest {
try Task.checkCancellation()
let filename = entry.name + "." + entry.ext
guard let url = bundle.url(
forResource: entry.name,
withExtension: entry.ext,
subdirectory: "Help"
) else { throw HelpError.missingBundleFile(filename) }
let data = try Data(contentsOf: url)
resources["/" + filename] = HelpResource(
mimeType: entry.mime, data: data
)
}
try Task.checkCancellation()
return HelpLibrary(resources: resources)
}
}
The request path selects a dictionary entry. It is never appended to a filesystem directory. Only the three filenames in bundled(in:) reach the bundle lookup.
Using percentEncodedPath makes the accepted URL spelling narrow: /index.html is a resource key, while /%69ndex.html is not an additional alias. We also reject credentials, ports, query strings, other hosts, and non-GET methods. A fragment is allowed because it identifies a location inside a document, not a separate file.
Do not confuse that policy with a promise to reject every spelling containing ... URL processing may normalize a path before the handler receives it. The useful guarantee is that the resulting request can retrieve only an explicit dictionary entry. There is no route from a request to an arbitrary app file.
The manifest supplies MIME types directly. A document should arrive as text/html; the stylesheet should arrive as text/css. Guessing based on the request or returning HTML for every missing asset makes failures harder to diagnose.
@concurrent keeps the synchronous bundle reads away from the caller’s actor. It does not make an individual Data(contentsOf:) call interruptible. We check cancellation between files and after the last read, using Swift’s cooperative cancellation model.
This version holds the whole library in memory. That is an intentional tradeoff for a few small text files, and it makes later resource requests cheap. Measure the total bytes if the library grows. A manual with hundreds of images needs a different loading and memory policy; changing the dictionary to a disk cache is a separate design task.
Reply with metadata, then bytes
The scheme handler can now serve already-loaded resources without starting a detached task for every request:
import WebKit
@available(iOS 26.0, macOS 26.0, *)
nonisolated struct HelpSchemeHandler: URLSchemeHandler {
let library: HelpLibrary
func reply(for request: URLRequest)
-> AsyncThrowingStream<URLSchemeTaskResult, any Error> {
AsyncThrowingStream { continuation in
do {
let resource = try library.resource(for: request)
guard let url = request.url else { throw HelpError.invalidRequest }
let response = URLResponse(
url: url,
mimeType: resource.mimeType,
expectedContentLength: resource.data.count,
textEncodingName: "utf-8"
)
continuation.yield(.response(response))
continuation.yield(.data(resource.data))
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
}
}
URLSchemeHandler returns an async sequence of results. The handler yields the response first, then the data, then finishes. Invalid or unknown requests finish with an error instead of a success page explaining that the real page was missing.
All three resources are UTF-8 text, so the encoding is explicit. If you later add binary images, give them their correct MIME type and omit the text encoding for those responses. Add each image to the manifest and permit its source in the CSP, such as img-src app-help:; the current policy blocks images.
There is no background producer to clean up in this handler: it synchronously enqueues one small response and one already-resident data value. If you replace this with asynchronous disk or network streaming, connect sequence termination to cancellation of that producer. An AsyncThrowingStream does not automatically manage work you launch and leave running.
Let CSS load without letting it become the help screen
Resource loading and document navigation have different jobs. The stylesheet must be available as a subresource, but following a link to it should not replace the help document.
Add a navigation decider and a page factory:
@available(iOS 26.0, macOS 26.0, *)
struct HelpNavigationDecider: WebPage.NavigationDeciding {
let library: HelpLibrary
@MainActor
func decidePolicy(
for action: WebPage.NavigationAction,
preferences: inout WebPage.NavigationPreferences
) async -> WKNavigationActionPolicy {
guard action.target?.isMainFrame == true,
!action.shouldPerformDownload,
library.allowsDocument(action.request)
else { return .cancel }
return .allow
}
}
@available(iOS 26.0, macOS 26.0, *)
@MainActor
func makeHelpPage(library: HelpLibrary) -> WebPage {
var configuration = WebPage.Configuration()
configuration.websiteDataStore = .nonPersistent()
configuration.defaultNavigationPreferences.allowsContentJavaScript = false
configuration.urlSchemeHandlers[URLScheme("app-help")!] = HelpSchemeHandler(
library: library
)
return WebPage(
configuration: configuration,
navigationDecider: HelpNavigationDecider(library: library)
)
}
Apple’s NavigationDeciding API lets the app decide before a navigation loads content. This policy accepts a main-frame navigation only when the request identifies one of our HTML resources. It cancels downloads, new-window targets, external URLs, and attempts to navigate directly to the stylesheet.
It does not decide every stylesheet or image request. That is why the resource manifest and the HTML’s CSP remain separate pieces. Registering a handler for app-help does not take over https traffic.
The page also disables content JavaScript and uses a nonpersistent website data store. Apple’s page configuration example demonstrates configuring that data store. Offline availability here comes from shipping the files, not from hoping a previous web visit warmed a cache.
Both force unwraps in the example are fixed URL/scheme literals under our control. Do not copy that treatment to URLs supplied by a document or server.
If the product needs an online support destination, expose a clearly named native link outside this help content and let the system open it. This sample intentionally keeps web navigation within its two documents. Avoid silently converting every rejected navigation into an external open action.
Own the page for the screen’s lifetime
Here is the complete screen. Use OfflineHelpView() in your app’s existing window, with an iOS 26/macOS 26 deployment target or an outer availability check.
import SwiftUI
@available(iOS 26.0, macOS 26.0, *)
@MainActor
struct OfflineHelpView: View {
@State private var page: WebPage?
@State private var failed = false
@State private var showFind = false
@State private var reloadID = UUID()
var body: some View {
NavigationStack {
Group {
if failed {
ContentUnavailableView {
Label("Help couldn't open", systemImage: "book.closed")
} actions: {
Button("Try again") { reloadID = UUID() }
}
} else if let page {
WebView(page)
.findNavigator(isPresented: $showFind)
} else {
ProgressView("Opening help…")
}
}
.navigationTitle("Help")
.toolbar {
Button("Find", systemImage: "magnifyingglass") {
showFind.toggle()
}
.disabled(page == nil || failed)
}
}
.task(id: reloadID) { await openHelp() }
.onDisappear { page?.stopLoading() }
}
private func openHelp() async {
page?.stopLoading()
page = nil
failed = false
showFind = false
do {
let library = try await HelpLibrary.bundled()
try Task.checkCancellation()
let newPage = makeHelpPage(library: library)
for try await _ in newPage.load(HelpLibrary.home) {
try Task.checkCancellation()
}
try Task.checkCancellation()
page = newPage
} catch {
guard !Task.isCancelled else { return }
failed = true
}
}
}
The task and disappearance handler sit on the stable NavigationStack, outside the loading/content/error branches. Switching from the progress indicator to the web view should not start another initialization task or stop the page that just appeared.
The view loads the library and finishes the initial navigation before installing the new WebPage. The progress indicator remains visible during that work, so a reader cannot click an internal link and supersede the initial load. A bundle or initial-load failure can show the retry control. Once open, WebKit follows the internal document links under the same navigation policy.
On departure, SwiftUI cancels the view task. Cancelling a task that is consuming the initial load sequence also stops that navigation’s resource loading, as documented in WebKit’s WebPage source. The explicit disappearance handler covers a later link navigation that may be loading after our initial task has finished. The catch block avoids displaying Swift task cancellation as a failure.
This is a small help screen, not a general browser. If your product needs persistent history, recovery from later web-process failures, or a policy for downloaded content, add those requirements explicitly. The initial load sequence is not a permanent observer of every future navigation.
Verify the library through WebKit
A resolver unit test can prove that a path exists in a dictionary. It cannot prove that WebKit actually applied the stylesheet.
The companion checks load the bundled HTML through a real WebPage, read the resulting document title, and inspect the computed body padding. Seeing 24px confirms that the relative CSS request passed through the custom handler and was applied. They also follow the resolved tips and return URLs through WebKit, check the fragment target, and exercise rejected document requests.
The smaller contract checks cover MIME types, response-before-data ordering, unknown paths, encoded aliases, unexpected hosts and query strings, non-GET methods, and a missing bundle file. These are useful failures to catch before replacing the sample pages with generated documentation.
Verified October 1, 2026: the exact published Swift blocks compile with Xcode 27.0 and Swift 6.4 for iOS 26 and macOS 26, under both ordinary and MainActor default isolation. The resource and navigation checks execute against the published code, and the native WebKit integration runs on the installed Mac. The iOS presentation, Find controls, accessibility behavior, and airplane-mode experience still need testing on the devices and OS versions you support.