通过打开文件启动应用程序时未打开WindowGroup

问题描述 投票:0回答:1
I创建了一个使用窗口组并利用

handlesExternalEvents

管理外部URL打开事件的应用程序,以防止WindowGroup再次打开新窗口。
一切都很好。窗口组不会触发新窗口,并成功接收OpenUrl事件。
唯一的问题是,当通过打开文件启动应用程序时,窗口组不会自动打开,因为

handlesExternalEvents

import SwiftUI import os.log @main struct HandleExternalEventsDemoApp: App { #if os(macOS) @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate #elseif os(iOS) @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate #endif let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "HandleExternalEventsDemoApp") var body: some Scene { WindowGroup { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() .handlesExternalEvents(preferring: ["MainWindowGroup"], allowing: ["*"]) .onOpenURL { url in logger.info("on open url: \(String(describing: url), privacy: .public)") } } // will not open a window on startup by open a file .handlesExternalEvents(matching: ["MainWindowGroup"]) } } #if os(macOS) import AppKit class AppDelegate: NSObject, NSApplicationDelegate { var openedURLs: [URL] = [] var didLaunched = false let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "AppDelegate") func application(_ application: NSApplication, open urls: [URL]) { // unhandled urls... logger.info("\(#function), urls: \(urls, privacy: .public)") } } #elseif os(iOS) import UIKit class AppDelegate: NSObject, UIApplicationDelegate { } #endif

我的问题是有什么解决方案可以解决这个问题?
handlesExternalEvents(matching:)

指定Swiftui为修改后场景的新实例的外部事件。
如果在窗户组场景中没有窗口,即使存在窗口,也没有什么可以处理外部的。

我想出了。感谢GPT。关键是

WindowGroup

很重要。我之前忽略了...
一旦我替换代码

conditions

.handlesExternalEvents(matching: ["MainWindowGroup"])

swift macos swiftui appkit
1个回答
0
投票
.handlesExternalEvents(matching: ["*"])

.handlesExternalEvents(preferring: ["MainWindowGroup"], allowing: ["*"])

它有效!
  • 在这里是gpt
    的答案
    Swiftui的Handlesexternalevents(匹配:)方法采用一组字符串,指示您的场景可以处理哪些外部事件。此组中的每个字符串都可以:
  • 路径或域模式匹配您的通用链接。
    自定义方案(例如myApp:// somepath)。
    
    一个通配符 *接受所有URLS。
    当外部事件(例如打开通用链接或自定义方案)到达时,SwiftUi将寻找一个场景,其Handlesexternalevents(匹配:)条件与传入的URL相匹配。如果找到匹配项,则该场景(及其视图层次结构)变得活跃以处理事件。
    
  • 当您需要处理外部URL时,您可以使用handlesexternalevents(匹配:)在Swiftui中:

匹配特定方案或路径


如果您的应用程序登记自定义方案(例如,myapp:// detail),则可以在集合中指定:

.handlesExternalEvents(preferring: ["*"], allowing: ["*"])

当带有url myapp的外部事件打开时,将触发此场景。
    匹配特定的通用链接
  • 支持您的应用程序通过
  • https://www.example.com
  • 支持通用链接。您可以匹配特定的路径:
  • WindowGroup { ContentView() } .handlesExternalEvents(matching: ["myapp://detail"])
this将处理外部开口到

Https://www.example.com/somepath

Https://www.example.com/anotherpath

.

匹配所有外部事件

如果您希望此场景处理您的应用程序可以打开的每个URL,则可以指定:
WindowGroup {
    ContentView()
}
.handlesExternalEvents(matching: ["www.example.com/somePath", "www.example.com/anotherPath"])

* *匹配所有路径,因此,如果要在一个地方处理所有URL,这是关键。这解决了必须单独指定每个可能的路径或方案的问题 - 使用[“*”]捕获所有内容。

WindowGroup { ContentView() } .handlesExternalEvents(matching: ["*"])

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.