For a few private projects the last couple of months I needed to implement a login system before the user could see the actual content.
It seemed like there were quite a few patterns people were using on how to implement such a system. The easiest way to go (imho :-)) is by creating a UIViewController which will serve the protected content and add it as the root view controller of your project. In that UIViewController you can then add a modal view controller which will present the login view.In the delegate message ‘viewDidAppear:’ you can then check if the user is already authenticated (e.g. from a previous session). In this example I check the state from a key in my NSUserDefaults dictionary, but you can implement your own authentication logic here. If the check returns a false answer, you can show the LoginViewController modally. Don’t forget to set the animated property to NO, so the user won’t see the content of your protected view controller for a second while the animation is running.
The reason why I do the check in viewDidAppear is because of the fact that only from this point you can show other (modal) view controllers. Before that point the view has not been added to the view hierarchy and you will get errors if you try to add something to it!
When the user has been authenticated, you just call dismissViewController: on the presentingViewController property and the login view controller will go away. The default transition is a slide down, but you can change it by adjusting the modalTransitionStyle property before executing the dismiss!
Alright enough chitchat … just go check out the code on GitHub and see for yourself. If you have any remarks, feel free to reply!
4 Responses
Hi! what I see in LoginViewController is that you have only one user, but what if you have several users? how your example could be modified in order to keep it working? how could this be modified if you simultaneously use your login and password to gain access to a DB that will be used to accomplish tasks within your app?
you just replace the code where I check for the credentials with your code to check with a database. You could use https://github.com/AFNetworking/AFNetworking to do this easily.
thanx!!!