Skip to content

dpearson2699/swift-ios-skills / skills/swiftui-webkit

swiftui-webkit

Verified

Embeds and controls web content in SwiftUI with WebKit for SwiftUI, including WebView, WebPage, navigation policies, JavaScript execution, observable page state, link interception, local HTML or data loading, and custom URL schemes. Use when building iOS 26+ article/detail views, help centers, in-app documentation, or other embedded web experiences backed by HTML, CSS, and JavaScript.

references/loading-and-observation.md

View on GitHub
# Loading and Observation

## Contents
- Simple `WebView(url:)`
- Controlled `WebPage` loading
- Observing progress and title
- Observing navigation events
- Ephemeral pages and custom user agents

## Simple `WebView(url:)`

Use `WebView(url:)` when the app only needs to display a URL and does not need explicit page control.

```swift
import SwiftUI
import WebKit

struct MarketingPageView: View {
    let url: URL

    var body: some View {
        WebView(url: url)
            .webViewBackForwardNavigationGestures(.enabled)
    }
}
```

This is the lowest-friction path for embedded content.

## Controlled `WebPage` loading

Create a `WebPage` when the app needs to drive loading itself.

Keep page ownership one-to-one with presentation: a `WebPage` can be bound to only one visible `WebView` at a time.

```swift
@Observable
@MainActor
final class ArticleModel {
    let page = WebPage()
    var lastError: String?

    func load(_ url: URL) async {
        do {
            for try await _ in page.load(URLRequest(url: url)) {
            }
        } catch {
            lastError = error.localizedDescription
        }
    }
}
```

```swift
struct ArticleDetailView: View {
    @State private var model = ArticleModel()
    let url: URL

    var body: some View {
        WebView(model.page)
            .task {
                await model.load(url)
            }
    }
}
```

You can also load:
- `for try await _ in page.load(url) { }`
- `for try await _ in page.load(html: htmlString, baseURL: baseURL) { }`
- `for try await _ in page.load(data, mimeType: "text/html", characterEncoding: "utf-8", baseURL: baseURL) { }`

Use the async sequence returned by a `load` call when you need to track that specific programmatic navigation. Use `page.navigations` for a broader stream covering both user and programmatic navigations.

## Observing progress and title

`WebPage` is observable, so SwiftUI can bind directly to its state.

```swift
struct ReaderView: View {
    @State private var page = WebPage()

    var body: some View {
        WebView(page)
            .navigationTitle(page.title ?? "Loading")
            .overlay(alignment: .top) {
                if page.isLoading {
                    ProgressView(value: page.estimatedProgress)
                        .padding()
                }
            }
            .task {
                do {
                    for try await _ in page.load(URLRequest(url: URL(string: "https://example.com/docs")!)) {
                    }
                } catch {
                    // Handle load failure.
                }
            }
    }
}
```

Useful properties:
- `title`
- `url`
- `isLoading`
- `estimatedProgress`
- `themeColor`
- `hasOnlySecureContent`
- `backForwardList`

## Observing navigation events

Use `currentNavigationEvent` for a lightweight current-state view. Use `navigations` to observe the full sequence of navigation events.

```swift
@MainActor
func observeNavigations(for page: WebPage) {
    Task {
        do {
            for try await event in page.navigations {
                switch event {
                case .startedProvisionalNavigation:
                    print("Navigation started")
                case .receivedServerRedirect:
                    print("Navigation redirected")
                case .committed:
                    print("Navigation committed")
                case .finished:
                    print("Navigation finished")
                @unknown default:
                    break
                }
            }
        } catch {
            print("Navigation failed: \(error)")
        }
    }
}
```

This is the right place to trigger follow-up work like parsing headings after a finished navigation. Treat thrown errors as normal navigation failures such as invalid URLs, provisional navigation failures, page closure, or web content process termination.

## Ephemeral pages and custom user agents

Use `WebPage.Configuration` when you need a nonpersistent page, custom user agent, or tighter loading rules.

```swift
@MainActor
func makeMetadataPage() -> WebPage {
    var configuration = WebPage.Configuration()
    configuration.loadsSubresources = false
    configuration.defaultNavigationPreferences.allowsContentJavaScript = false
    configuration.websiteDataStore = .nonPersistent()

    let page = WebPage(configuration: configuration)
    page.customUserAgent = "MetadataBot/1.0"
    return page
}
```

Use nonpersistent pages when you want an isolated web session or metadata fetch path without shared cookies or long-lived website data.
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall