Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: way to check that WINDOW(not app) activated (become foreground)

I need to call some method on event when my app become foreground

(I'm using ViewModel for each view, so I can call sth not only from view)

As example:

  1. my app is runned;

  2. changed foreground window to Safari app.

  3. Changed foreground window to my app -> some method called.

With .onChange(of: scenePhase) -> .active nothing happens with this scenario

so those code is not solution for me:

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase
    var body: some View {
        TestView()
            .onChange(of: scenePhase) { phase in
                switch phase {
                    case .active:
                        print("App is active")
                    default:
                        break
                }
            }
    }
}
like image 560
Andrew Avatar asked Oct 25 '25 03:10

Andrew


1 Answers

You could use the environment variable controlActiveState as follows:

@Environment(\.controlActiveState) var controlActiveState
like image 107
user1046037 Avatar answered Oct 27 '25 18:10

user1046037



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!