How to update a view when returning from background
Hello my fellow developers, Leo here.
Today we'll dive into a problem that I certainly all iOS developers face from time to time and because of apple's API wording the solution isn't intuitive as it should be. Let's explore this edge case of updating view that haunts all iOS developers.
I need to update my ViewController/View every time the app return from background. Ex: when switching you switch from app A to B, and return to A.
We all intuitively write all the behaviour that should run every time a view appear inside the method viewWillAppear because... That's exactly what we need, we need to run some setup code every time the "view will appear". So we are biased to think when the app goes to background ( ex: when switching apps, or calling an app inside other app etc), when it returns it will run the viewWillAppear method but it doesn't.
And why is that?
If you thing about it the view life cycle is responsible for actions made INSIDE your app, but switching apps isn't that. When you switch app is a system action outside your app so as far as your app's concern the view it is shown never left. We need other tool to update the UI that is focused on the app management per se.
For < iOS 13 :
You can use the AppDelegate methods OR you can add a observer into the view like this:
UIApplication.willEnterForegroundNotification : NotificationCenter.default.addObserver(self, selector: #selector(setupUIReturnFromBackground), name: UIApplication.willEnterForegroundNotification, object: nil)
For iOS >= 13 :
In other hand from this version and so on you will start to see more and more from now on you will probably use the SceneDelegate methods like : sceneWillEnterForeground.
If you go for AppDelegate or SceneDelegate methods be sure to not pollute the file with information it doesn't need to know. Be sure to have some Notification Center or RxSwift listeners to do that for you.
And that's it! I hope you enjoy the content like I did and if learned something new let me now! The feedbacks are always welcome.
Thanks for the reading and... That's all folks!