Action after back background application

Asked

Viewed 79 times

1

I have a webview on android that always checks if there is internet when returning from the background checking if the connection status has been changed if it is offline the app sends the user to a screen "reconnect and try again" using the code below:

protected void onResume() {
        super.onResume();
        mWebView.onResume();
        if (isConnected(getApplicationContext())){
        } else {
            Intent i = new Intent(MainActivity.this, off.class);
            startActivity(i);
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            finish();
        }
    }

So far so good I made an Ios version of this webview but I could not play this check when the app returns in the background, how do I play this "onresume" on Ios Swift? (the code checking the connection status I already have)

2 answers

3


Complementing Rodrigo’s response, despite the viewDidAppear be a possibility, this method not called when the app returns in the background. Actually viewDidAppear is called when the Viewcontroller view has become visible. This does not always occur when the app comes into focus. If the intention is to actually notice when the app gets the focus, rather than depending on the life cycle of UIViewController (ex: viewWillAppear, viewDidAppear), the correct is to use the application lifecycle methods (UIApplication). In this case you can use applicationWillEnterForeground: or applicationDidBecomeActive:. They are called in the Appdelegate when events happen.

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        return true
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
    }
}

If it makes more sense in your code for these callbacks to be fired in a specific class, such as a Uiviewcontroller for example, you can use the notification system.

NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil) { _ in
    //...
}

2

According to the life cycle iOS, similar to the onResume Android, would be the viewDidAppear():

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //sua lógica
}

In the documentation it also says about the viewWillAppear(), that would be a step before the viewDidAppear(). See which one suits you best!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.