Swiftui Webkit

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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.

AI 產生的概覽

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

功能
此技能提供參考指引,說明如何在 SwiftUI 中使用 WebView 與 WebPage 顯示網頁內容、載入 URL 或本機 HTML、觀察頁面狀態、套用導覽原則,以及呼叫 JavaScript。內容涵蓋用於內建或離線內容的自訂 URL 配置、WebView 自訂(例如上一頁/下一頁手勢與頁內尋找)、常見錯誤,以及審查清單。它僅包含說明,不會產生檔案或指令碼。
適用情境
適用於建置 iOS 26+、iPadOS 26、macOS 26 或 visionOS 26 的 SwiftUI App,且需要嵌入式網頁介面、App 自有 HTML 內容、JavaScript 支援的頁面互動或導覽原則控制的場景。也適合由 HTML、CSS 與 JavaScript 支援的文章或詳細資料檢視、說明中心與 App 內文件。
執行需求
需要代理在鎖定 iOS 26、iPadOS 26、macOS 26 或 visionOS 26 的 SwiftUI 專案中,使用 WebKit for SwiftUI API 進行作業。除閱讀隨附的參考文件外,不需要指令碼、套件、認證或網路存取。

SwiftUI WebKit

Embed and manage web content in SwiftUI using the native WebKit-for-SwiftUI APIs introduced for iOS 26, iPadOS 26, macOS 26, and visionOS 26. Use this skill when the app needs an integrated web surface, app-owned HTML content, JavaScript-backed page interaction, or custom navigation policy control.

Contents

Choose the Right Web Container

Use the narrowest tool that matches the job.

NeedDefault choice
Embedded app-owned web content in SwiftUIWebView + WebPage
iOS/iPadOS modal browsing with Safari behaviorSFSafariViewController
macOS or visionOS browse-out behavioropenURL / default browser
OAuth or third-party sign-inASWebAuthenticationSession
Back-deploy below iOS 26 or use missing legacy-only WebKit featuresWKWebView fallback

Prefer WebView and WebPage for modern SwiftUI apps targeting iOS 26+ when the new API surface covers the feature. Apple’s WWDC25 guidance frames existing UIKit/AppKit WebKit wrappers in SwiftUI apps as good candidates to try migrating, not as a blanket mandate to delete every fallback.

Do not use embedded web views for OAuth. That stays an ASWebAuthenticationSession flow.

Displaying Web Content

Use the simple WebView(url:) form when the app only needs to render a URL and SwiftUI state drives navigation.

swift
import SwiftUIimport WebKit
struct ArticleView: View {    let url: URL
    var body: some View {        WebView(url: url)    }}

Create a WebPage when the app needs to load requests directly, observe state, call JavaScript, or customize navigation behavior.

A WebPage can be associated with only one WebView at a time. Create separate WebPage instances for multiple visible web views.

swift
@Observable@MainActorfinal class ArticleModel {    let page = WebPage()
    func load(_ url: URL) async throws {        for try await _ in page.load(URLRequest(url: url)) {        }    }}
struct ArticleDetailView: View {    @State private var model = ArticleModel()    let url: URL
    var body: some View {        WebView(model.page)            .task {                try? await model.load(url)            }    }}

See references/loading-and-observation.md [blocked] for full examples.

Loading and Observing with WebPage

WebPage is an @MainActor observable type. Use it when you need page state in SwiftUI.

Common loading entry points:

  • load(URLRequest)
  • load(URL)
  • load(html:baseURL:)
  • load(_:mimeType:characterEncoding:baseURL:)

Common observable properties:

  • title
  • url
  • isLoading
  • estimatedProgress
  • currentNavigationEvent
  • backForwardList
swift
struct ReaderView: View {    @State private var page = WebPage()
    var body: some View {        WebView(page)            .navigationTitle(page.title ?? "Loading")            .overlay {                if page.isLoading {                    ProgressView(value: page.estimatedProgress)                }            }            .task {                do {                    for try await _ in page.load(URLRequest(url: URL(string: "https://example.com")!)) {                    }                } catch {                    // Handle load failure.                }            }    }}

When you need to react to every navigation, observe the navigation sequence rather than only checking a single property.

swift
Task {    do {        for try await event in page.navigations {            // Handle started, redirect, committed, or finished events.        }    } catch {        // Handle WebPage.NavigationError or cancellation.    }}

See references/loading-and-observation.md [blocked] for stronger patterns and the load-sequence examples.

Navigation Policies

Use WebPage.NavigationDeciding to allow, cancel, or customize navigations based on the request or response.

Typical uses:

  • keep app-owned domains inside the embedded web view
  • cancel external domains and hand them off with openURL
  • intercept special callback URLs
  • tune NavigationPreferences
swift
@MainActorfinal class ArticleNavigationDecider: WebPage.NavigationDeciding {    var urlToOpenExternally: URL?
    func decidePolicy(        for action: WebPage.NavigationAction,        preferences: inout WebPage.NavigationPreferences    ) async -> WKNavigationActionPolicy {        guard let url = action.request.url else { return .allow }
        if url.host == "example.com" {            return .allow        }
        urlToOpenExternally = url        return .cancel    }}

Keep app-level deep-link routing in the navigation skill. This skill owns navigation that happens inside embedded web content.

See references/navigation-and-javascript.md [blocked] for complete patterns.

JavaScript Integration

Use callJavaScript(_:arguments:in:contentWorld:) to evaluate JavaScript functions against the page.

Pass a JavaScript function body, not a wrapped function declaration or call expression. Prefer arguments for Swift-provided values instead of interpolating untrusted strings into the script.

swift
let script = """const headings = [...document.querySelectorAll('h1, h2')];return headings.map(node => ({    id: node.id,    text: node.textContent?.trim()}));"""
let result = try await page.callJavaScript(script)let headings = result as? [[String: Any]] ?? []

You can pass values through the arguments dictionary and cast the returned Any into the Swift type you actually need.

swift
let result = try await page.callJavaScript(    "return document.getElementById(sectionID)?.getBoundingClientRect().top ?? null;",    arguments: ["sectionID": selectedSectionID])

Handle empty and JavaScript null results deliberately: no explicit return produces nil, while an explicit JavaScript null returns NSNull.

Important boundary: the native SwiftUI WebKit API clearly supports Swift-to-JavaScript calls, but it does not expose an obvious direct replacement for WKScriptMessageHandler. If you need coarse JS-to-native signaling, a custom navigation or callback-URL pattern can work, but document it as a workaround pattern, not a guaranteed one-to-one replacement.

See references/navigation-and-javascript.md [blocked].

Local Content and Custom URL Schemes

Use WebPage.Configuration and URLSchemeHandler when the app needs bundled HTML, offline documents, or app-provided resources under a custom scheme.

swift
var configuration = WebPage.Configuration()configuration.urlSchemeHandlers[URLScheme("docs")!] = DocsSchemeHandler(bundle: .main)
let page = WebPage(configuration: configuration)for try await _ in page.load(URL(string: "docs://article/welcome")!) {}

Use this for:

  • bundled documentation or article content
  • offline HTML/CSS/JS assets
  • app-owned resource loading under a custom scheme

Do not overuse custom schemes for normal remote content. Prefer standard HTTPS for server-hosted pages.

See references/local-content-and-custom-schemes.md [blocked].

WebView Customization

Use WebView modifiers to match the intended browsing experience.

Useful modifiers and related APIs:

  • webViewBackForwardNavigationGestures(_:)
  • findNavigator(isPresented:)
  • webViewScrollPosition(_:)
  • webViewOnScrollGeometryChange(...)

Apply them only when the user experience needs them.

  • Enable back/forward gestures when people are likely to visit multiple pages.
  • Add Find in Page when the content is document-like.
  • Sync scroll position only when the app has a sidebar, table of contents, or other explicit navigation affordance.

Apple’s HIG also applies here: support back/forward navigation when appropriate, but do not turn an app web view into a general-purpose browser.

Common Mistakes

  • Using WKWebView wrappers by default in an iOS 26+ SwiftUI app instead of starting with WebView and WebPage
  • Using embedded web views for OAuth instead of ASWebAuthenticationSession
  • Reaching for WebPage only after building a plain WebView(url:) path that now needs state, JS, or navigation control
  • Treating callJavaScript as a direct replacement for WKScriptMessageHandler
  • Passing a callable JavaScript wrapper to callJavaScript instead of only the function body
  • Iterating page.navigations without try/catch even though navigation failure terminates the sequence by throwing
  • Binding the same WebPage to multiple visible WebView values
  • Keeping all links inside the app when external domains should open outside the embedded surface
  • Treating SFSafariViewController as the cross-platform browse-out answer on macOS or visionOS instead of using default-browser/openURL behavior
  • Building a browser-style app shell around WebView instead of a focused embedded experience
  • Using custom URL schemes for content that should just load over HTTPS
  • Forgetting that WebPage is main-actor-isolated

Review Checklist

  • WebView and WebPage are the default path for iOS 26+ SwiftUI web content
  • ASWebAuthenticationSession is used for auth flows instead of embedded web views
  • WebPage is used whenever the app needs state observation, JS calls, or policy control
  • Navigation policies only intercept the URLs the app actually owns or needs to reroute
  • External domains open externally when appropriate
  • JavaScript return values are cast defensively to concrete Swift types
  • callJavaScript uses a function body and passes Swift values through arguments
  • page.navigations loops use for try await and handle thrown navigation errors
  • Each visible WebView(page) owns a distinct WebPage
  • Custom URL schemes are used only for real app-owned resources
  • Back/forward gestures or controls are enabled when multi-page browsing is expected
  • SFSafariViewController is limited to iOS/iPadOS Safari-style modal browsing; macOS and visionOS browse-out flows use platform default browser behavior
  • The web experience adds focused native value instead of behaving like a thin browser shell
  • Fallback to WKWebView is justified by deployment target or missing API needs

References

  • Loading and observation: references/loading-and-observation.md [blocked]
  • Navigation and JavaScript: references/navigation-and-javascript.md [blocked]
  • Local content and custom schemes: references/local-content-and-custom-schemes.md [blocked]
  • Migration and fallbacks: references/migration-and-fallbacks.md [blocked]

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/swiftui-webkit提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Uikit Interop

dpearson2699

指導使用可表示視圖、託管控制器、協調器與共享可觀察狀態來橋接 UIKit 與 SwiftUI。

Software Development1.1K2 個月前更新