Detecting when a SwiftUI MenuBarExtra with window style is opened
In theory when using a SwiftUI MenuBarExtra with the window style, you should be able to use scenePhase environment variable to detect when the menu bar button is clicked, and the window is shown.
Unfortunately this does not work:
import SwiftUI
@main
struct AppleWatchAlexaApp: App {
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
MenuBarExtra("Voice in a Can", image: "MenuBarIcon") {
ContentView()
.frame(width: 1280, height: 800)
}
.menuBarExtraStyle(.window)
.onChange(of: scenePhase) {newPhase in
print("New phase is \(newPhase)")
}
}
}
Instead as a workaround I’ve found I can observe the keyWindow Application property. When it is not nil, the app is visible:
import SwiftUI
@main
struct AppleWatchAlexaApp: App {
@State var observer: NSKeyValueObservation?
var body: some Scene {
MenuBarExtra("Voice in a Can", image: "MenuBarIcon") {
ContentView()
.frame(width: 1280, height: 800)
.onAppear {
observer = NSApplication.shared.observe(\.keyWindow) { x, y in
print("Is visible: \(NSApplication.shared.keyWindow != nil)")
}
}
}
.menuBarExtraStyle(.window)
}
}
If you use popups in your app then you’ll need to work around them, since when they are displayed the keyWindow
will go to nil.
Comment on this post here