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"])
.handlesExternalEvents(matching: ["*"])
到
.handlesExternalEvents(preferring: ["MainWindowGroup"], allowing: ["*"])
它有效!
在这里是gpt的答案
Swiftui的Handlesexternalevents(匹配:)方法采用一组字符串,指示您的场景可以处理哪些外部事件。此组中的每个字符串都可以:
自定义方案(例如myApp:// somepath)。一个通配符 *接受所有URLS。 当外部事件(例如打开通用链接或自定义方案)到达时,SwiftUi将寻找一个场景,其Handlesexternalevents(匹配:)条件与传入的URL相匹配。如果找到匹配项,则该场景(及其视图层次结构)变得活跃以处理事件。
匹配特定方案或路径
.handlesExternalEvents(preferring: ["*"], allowing: ["*"])
当带有url myapp的外部事件打开时,将触发此场景。
WindowGroup {
ContentView()
}
.handlesExternalEvents(matching: ["myapp://detail"])
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: ["*"])