Neurax Neurax - 1 month ago 13
Swift Question

applicationDidBecomeActive keep logged in similar to instagram

What I'm looking for is a mechanism to keep my app from resetting to the root view controller every time the application gets backgrounded or goes inactive. There are many apps out there that operate this way, namely Instagram, eBay, etc.

My instincts told me initially to poke into the AppDelegate's

applicationWillEnterForeground
method, where I would try to present the viewcontroller I'm after, however when I instantiate the viewController, I can present it, but without the navigation controller that normally be there.

This makes me think that I need to save the "state" of the application (maybe the NavigationController's stack?) and then restore the stack somehow when it gets relaunched.

I have watched the execution timings of each event and notice that closing the application and relaunching it will start the application fresh. I assume that my
NSUserDefaults
are still in place and thus could be checked for a logged in user. This could help determine which view in the navigation controller to push to (either login or dashboard).

Any direction is greatly appreciated.




The most revealing answer in this post was the use of some storage (NSUserDefaults) in order to store persistent data across uses.

For my specific case, this was storing a key holding user info. Then when the application loads, the would-be first view comes up, but if that key is missing, will modally pull a login view in front of it.

Answer

To do this I would use NSUserDefaults to store the current view of the app and then switch to that view when your app finishes launching. See the answers to this question: Swift: How to store user preferences?