0

I am building an app in swift which interacts with an API. There a two ways a user can be logged out, by clicking a logout button or by receiving a 401 response when calling the API.

I plan on using NSNotificationCenter in my API class to broadcast an event when an unsuccessfully response is received so generic handling of things like 401, 400, 500 can be handled in one place outside of the API class.

To prevent duplicating the logic involved with logging out in multiple places I have created a Class which will clear any existing tokens and present the login view controller. This class can then be used when the logout button is clicked in the view controller or when a 401 response is picked up by the response observer.

My problem is, since the logic is not inside a view controller I am unsure how I can present the login view controller as I do not have access to the method self.presentViewController

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ben_hawk
  • 2,476
  • 7
  • 34
  • 59
  • Your class can tell the app delegate to present the view controller or switch your root view controller. (See [this example](http://stackoverflow.com/a/24666140/1445366). – Aaron Brager Jun 02 '15 at 21:23

1 Answers1

0

You're going to need to pass that responsibility to a view controller.

How I've handled this in the past is using a key-value observer (or RAC) to monitor the active token. When that token goes away, I swap out the root controller.

Where you do this depends on how you've structured things. The app delegate is a reasonable spot.

David McGraw
  • 5,157
  • 7
  • 36
  • 36
  • Thanks I am fairly close now. I created an event through the notification centre that is handled in the app delegate. My only issue now is that I cannot get the current view controller to use to present the login view controller. Since the root view controller is not active I get the error "Warning: Attempt to present on whose view is not in the window hierarchy!" – Ben_hawk Jun 03 '15 at 10:19