Search code examples
iosswiftswiftuiviewwillappearuiscenedelegate

Detect when a specific view is opened from the background in SwiftUI?


If I have a SwiftUI view and I put it into the background (i.e. hit the home button once on the iPhone) and then reopen it again, I would like to trigger some action.

My first thought was to make use of the

.onAppear{}

modifier, but, after some testing, this does not apply for views that are entering the foreground after being in the background.

There does not seem to a SwiftUI equivalent to the UIKit ViewWillAppear.

I was thinking maybe the scene delegate could be useful here, as it does provide the function:

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
}

but I'm not sure if there is an efficient way to use this function to trigger an action in a view when the view enters the foreground from the background.

Any thoughts on this would be appreciated.


Solution

  • sceneWillEnterForeground should work as detailed https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_foreground

    Alternatively if you only have specific components that care about the foregrounding action you can subscribe to the notification center as detailed https://www.hackingwithswift.com/books/ios-swiftui/how-to-be-notified-when-your-swiftui-app-moves-to-the-background