lhbortho
lhbortho

Reputation: 177

Swift IOS keep view controller running in background after pop

My app consists of two views. The first one is a GMSMapView and the second one is used to connect to a Bluetooth device that sends coordinates.

After the Bluetooth device is connected, I use a delegate to send the information back to the map view and move a marker around. To transition between views I was previously using segues, this didn't stop the Bluetooth view controller and the data made its way like I wished to the map view.

I ran into the problem of my map view being reinitiated so I decided to use a navigation controller. Now I use a push segue to get to my second view, and pop to come back to the same instance of the first one. Great, that worked! The issue I have now is that popping the second view seems to stop it completely from running in the background like it used to. Is there a way to keep it running in the background like it did before?

What I'm currently using to pop the second view is

self.navigationController?.popViewControllerAnimated(true)

Any idea would be appreciated! Thanks!

Upvotes: 1

Views: 3786

Answers (1)

matt
matt

Reputation: 535890

A popped view controller does not "stop running". It is returned to you, and if you don't retain it, it is completely destroyed.

If you don't want that to happen, retain it when it is returned. You are currently ignoring the returned view controller:

 self.navigationController?.popViewControllerAnimated(true)

Instead, keep a reference to it:

self.mySecondViewController = 
    self.navigationController?.popViewControllerAnimated(true)

Be warned, however, that this is a very unusual architecture. You will not be able to use the storyboard segue to push again, because it will push a different copy. It would be better to abandon your navigation controller architecture entirely, as it is completely unsuited to the idea of a view controller persisting after it is popped. If you want an architecture where two view controllers persist simultaneously, you would be better off using a UITabBarController — or, even better, reorganize your app completely. The notion that you need the view controller to persist after being popped is a "bad smell": it means that you have put the functionality in the wrong place. Put the functionality in a place that does persist, rather than forcing the view controller to persist in some artificial way.

Upvotes: 4

Related Questions