You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI使用Window而非WindowGroup时如何响应自定义Scheme URL

问题描述

把SwiftUI应用的主窗口从WindowGroup改成单Window后,之前能用的.onOpenURL突然不触发了,怎么才能让单窗口的应用正常响应URL打开请求?

解决方案

方法1:直接给App结构体加.onOpenURL

别把.onOpenURL绑在Window上,直接挂到App层级就行——不管是多窗口的WindowGroup还是单窗口的Window,这样都能稳稳捕获到URL请求:

@main
struct MyApp: App {
    var body: some Scene {
        Window("主窗口", id: "main") {
            ContentView()
        }
    }
    // 直接在App结构体上绑定onOpenURL
    .onOpenURL { url in
        print("收到URL:\(url)")
        // 这里写你的URL处理逻辑,比如把URL传给ContentView
    }
}

方法2:用应用代理捕获(适合复杂场景)

如果需要更底层的控制,比如处理批量URL或者和系统交互更深入,用代理适配器就行:

macOS版本:

class AppDelegate: NSObject, NSApplicationDelegate {
    func application(_ application: NSApplication, open urls: [URL]) {
        guard let targetUrl = urls.first else { return }
        print("通过代理收到URL:\(targetUrl)")
        // 处理URL逻辑,比如用通知或者可观察对象把URL传给视图
    }
}

@main
struct MyApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        Window("主窗口", id: "main") {
            ContentView()
        }
    }
}

iOS/iPadOS版本:

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        print("通过代理收到URL:\(url)")
        // 写你的URL处理逻辑
        return true
    }
}

@main
struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        Window("主窗口", id: "main") {
            ContentView()
        }
    }
}

额外提示

  • 如果要把URL传给ContentView处理,可以用@ObservableObject或者SwiftUI的状态绑定,比如在App里定义一个可观察对象,把收到的URL赋值给它,然后在ContentView里监听这个对象的变化。
  • 别忘了在项目的Info.plist里配置好对应的URL Scheme,不然系统不会把URL请求发给你的应用。

内容的提问来源于stack exchange,提问作者RopeySim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:27:42