0

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)
            }
        }
    }
gcstr
  • 1,466
  • 1
  • 21
  • 45
  • Could you provide an example of the code that causes the error? – nickreps Feb 25 '23 at 19:54
  • Sure @nickreps. I just updated the description with and example of what I mean by "from outside of a view" – gcstr Feb 25 '23 at 19:59
  • Thanks. I cannot replicate the error as I do not have `KeyboardShortcuts` available. Is this a swift package? Without having the exact error, my best guess here is the issue is due to using an `@EnvironmentObject` inside your `ObservableObject` class - as I do not believe this is allowed. You may need to approach this using dependency injection. [Here is a potentially relevant post on stackoverflow](https://stackoverflow.com/questions/63625295/swiftui-how-to-get-environmentobject-data-inside-observableobject) – nickreps Feb 25 '23 at 20:24

0 Answers0