Search code examples
swiftobservablelifecycle

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.


Solution

  • 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
        }
    }