If I want to open a new window in SwiftUI, I could use the following code:
struct ContentView: View {
@Environment(\.openWindow) var openWindow
var body: some View {
Button("Open the window") {
openWindow(id: "the-window")
}
}
}
But if I try to open a window using the same code outside of a view, the compiler warns that it won't work:
Accessing Environment<OpenURLAction>'s value outside of being installed on a View. This will always read the default value and will not update.
How can I open a window in SwiftUI lifecycle from outside of a view? e.g.: from a hotkey listener.
Edit:
Here is an example of the code that raises the warning:
@MainActor
final class AppState: ObservableObject {
@Environment(\.openURL) var openURL
init() {
KeyboardShortcuts.onKeyDown(for: .doubleClick) {
if let url = URL(string: "myapp://the-window") {
self.openURL(url)
}
}
}