How to update a view when returning from background

Hello, my fellow developers, Leo here. Today we will learn how to update a view when returning from the background.

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.

 

Problem

I need to update my ViewController/View every time the app return from the background. Ex: when switching you switch from app A to B, and return to A.

We all intuitively write all the behavior that should run every time a view appears 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 the background ( ex: when switching apps, or calling an app inside another app, etc), when it returns it will run the *viewWillAppear* method but it doesn’t.

And why is that?

If you think about it the view life cycle is responsible for actions made INSIDE your app, but switching apps isn’t that. When you switch apps is a system action outside your app so as far as your app’s concerned the view it is shown never left. We need another tool to update the UI that is focused on app management per se.

 

Solution – Update a view when returning from the background

For < iOS 13 :

You can use the AppDelegate methods OR you can add an observer into the UIView like this:

NotificationCenter.default.addObserver(self, selector: #selector(setupUIReturnFromBackground), name: UIApplication.willEnterForegroundNotification, object: nil)

Simple, right?

 

For iOS >= 13 :

On the 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 not to pollute the file with information it doesn’t need to know. Be sure to have some Notification Center or RxSwift listeners do that for you.

 

Summary

Today we learned how to update a view when returning from the background state and react to going foreground again.

That’s all my people, I hope you liked reading this article as much as I enjoyed writing it. If you want to support this blog you can Buy Me a Coffee or leave a comment saying hello. You can also sponsor posts and I’m open to freelance writing! You can reach me on LinkedIn or Twitter and send me an e-mail through the contact page.

Thanks for the reading and… That’s all folks.

Credits – image

Share this post:

Related posts

Sponsor