user9413194
user9413194

Reputation: 119

How can I detect when the swift application is foreground from the background?

I want to run a function in my application if the application is not running from the background. How can I do that?

I cannot use applicationDidBecomeActive and applicationDidEnterBackground because I need to detect the situation when it comes from the background, not the state when it is being taken to the background or when it is opened. Also, when the application is opened for the first time, it will not work when it comes from the background.

Upvotes: 4

Views: 6274

Answers (3)

Atiar Talukdar
Atiar Talukdar

Reputation: 746

struct ContentView: View {
    @Environment(\.scenePhase) var scenePhase

    var body: some View {
        Text("Hello, world!")
            .padding()
            .onChange(of: scenePhase) { newPhase in
                if newPhase == .active {
                    print("Active")
                } else if newPhase == .inactive {
                    print("Inactive")
                } else if newPhase == .background {
                    print("Background")
                }
            }
    }
}

Upvotes: 2

gcharita
gcharita

Reputation: 8327

You probably need willEnterForegroundNotification.

Posted shortly before an app leaves the background state on its way to becoming the active app.

Keep in mind thow that this notification posted olso after application(_:didFinishLaunchingWithOptions:) when opening the application for the first time.

When application opens for the first time the applicationState is inactive and when the application comes from the background the applicationState is background.

So, your code will be something like this:

token = NotificationCenter.default.addObserver(
    forName: UIApplication.willEnterForegroundNotification,
    object: nil,
    queue: .main
) { (notification: Notification) in
    if UIApplication.shared.applicationState == .background {
        // Came from the background
    }
}

Upvotes: 4

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119128

Check the current state:

Use UIApplication.shared.applicationState.

switch UIApplication.shared.applicationState {
case .active: // The app is running in the foreground and currently receiving events.
case .inactive: // The app is running in the foreground but is not receiving events. This might happen as a result of an interruption or because the app is transitioning to or from the background.
case .background: // The app is running in the background.
}

Upvotes: 7

Related Questions