Reputation: 5547
My app has the following flow if the user is logged in
Loading Screen -----> Main Screen -----> Rest of App
and the following flow if he's not :
Loading Screen -----> Login Screen -----> Main Screen -----> Rest of App
Now I am implementing the Logout feature. I have added the following code into main Screen
:
func handleLogout() {
if self.presentingViewController != nil {
var vc = self.presentingViewController
while ((vc!.presentingViewController) != nil) {
vc = vc!.presentingViewController
}
vc?.dismissViewControllerAnimated(true, completion: {
})
}
}
This works fine if the 1st
path is followed (the user was logged in when the app was launched) as the app returns to the Loading Screen
and then loads up the Login Screen
as expected. However, if the 2nd
path was followed (the user was not logged in when the app was launched, and Login Screen
has been used) this code leads to the Login Screen
being opened directly and the whole logout process failing. Is there a way I can ensure that the Loading Screen
is the one which is always loaded by this code regardless of which of the two paths have been followed.
Upvotes: 0
Views: 62
Reputation: 270770
Use unwind segues!
You basically add an unwind segue connecting your "main screen" and "login screen". Give it an identifier and you can initiate the segue whenever you want. In handleLogout
:
func handleLogout() {
self.performSegueWithIdentifier("your identifier", sender: self)
}
For details of how to create an unwind segue: https://www.andrewcbancroft.com/2015/12/18/working-with-unwind-segues-programmatically-in-swift/
Upvotes: 1
Reputation: 1
If you are using Storyboards, I would suggest creating storyboard that is used purely for your login view/s. Then in the AppDelegate DidFinishLoading method, you can show the login storyboard if they need to login or show the main storyboard if they are already logged in. You can swap out storyboards at anytime and its easy to do. That will help simplify the flow a bit. This is what I usually do in my apps. If you need sample code just let me know.
Upvotes: 0
Reputation: 2569
This is just a suggestion here goes:
In AppDelegate
file you can do something similar to this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//Implement this method
let userLoggedIn = isUserLoggedIn();
if !userLoggedIn {
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
//Instantiate the login view controller
window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("login")
window?.makeKeyAndVisible()
}
return true
}
Now when the app starts it'll first check the user's login state and display the appropriate view.
Note: this is assuming you use storyboards and the root view controller is set to the Main Screen
Upvotes: 0