Article
Why isn’t viewWillAppear getting called?
February 27, 2019
Why were you expecting it to be?
Most likely — you want to know that your user is about to see a screen.
There are all sorts of useful reasons to want that. Maybe you want to track an analytics screen view, or trigger a data fetch to keep your screen fresh. Whatever your aim, someone probably told you to check out viewWillAppear
— Well, bad news. It’ll work for those goals, but only sometimes.*
The Simple Answer
The technical reason for when viewWillAppear
gets called is simple.
Notifies the view controller that its view is about to be added to a view hierarchy.
It can’t be any view hierarchy — it has to be the one with aUIWindow
at the root (not necessarily the visible window).
This is fine if you’re jumping from tab to tab or pushing and popping from a UINavigationController
. iOS is removing your view from the view hierarchy and inserting it back in each time. The view remains in memory during all this so viewDidLoad
won’t be called repeatedly.
However, you’ll get into trouble when you start presenting views over your current screen, because sometimes* it will remove the underlying view, but sometimes* it won’t.
Presenting your View Controller
It all depends on how you’re presenting your modal view. iOS prefers to remove the underlying view if it can (memory is precious). But if your designers insist on keeping that underlying view around, you can ask iOS to keep it by setting the correct .modalPresentationStyle
.
Here are you choices and whether or not it will trigger viewWillAppear
on its parent view when dismissed: