Simple login view in Swift

There comes a time when login within an app is necessary to access a secure resource. This post walks through the implementation of a simple login view in Swift. There a number of things new Mobile App developers can find confusing and difficult:
  1. How do I display a login view if the user is not logged in?
  2. How do I keep a user logged in?
  3. How do I display x view of my app once the user is logged in?
This post will help you with these important topics. Future posts will deal with other things which are important such as validating the username and password before sending a request to the server, displaying validation messages to users, dealing with failed login attempts and what to do when the OAuth Token becomes invalid.

Backend Service to deal with login

Writing the service which authenticates a user is out of scope for this post so I have produced a simple service in Apigee which will return an OAuth Token. There is no validation on this service for this example though so any username and password will return an OAuth Token.
To get an OAuth Token from the OAuth service you need to make a POST request as follows:
curl -X POST
-H "Content-Type:application/x-www-form-urlencoded"
-d 'client_id=yA0ac1klHaXYDJ5HPHN4sVVxpX1Vem1A&client_secret=zJA8WNmmxe4UXR0G&login=dave&password=secret&grant_type=password'
If successful you should get a response from the OAuth Service with the following information:
{
issued_at: "1413439280292"
scope: ""
application_name: "74e981ff-f5b3-4ceb-b559-14e33ceb4a71"
refresh_token_issued_at: "1413439280292"
status: "approved"
refresh_token_status: "approved"
api_product_list: "[Blog]"
expires_in: "1799"
organization_id: "0"
token_type: "BearerToken"
refresh_token: "n7G3ahu2JHJUnLSvZOB7SBDNYcbUi02p"
client_id: "yA0ac1klHaXYDJ5HPHN4sVVxpX1Vem1A"
access_token: "qdAhTA4z1f6REjoZVzG3jdfZmGRE"
organization_name: "developerdave"
refresh_token_expires_in: "86399"
refresh_count: "0"
}
view rawOAuth Token Response hosted with ❤ by GitHub

Getting Started With Showing A Login Form

Start up Xcode 6 and go to File -> New -> Project and choose the Single View Application template and click Next.
Single View Application
Fill out the details as follows:
  • Product Name: LoginSample
  • Language: Swift
  • Devices: iPhone
Product Details

Displaying a login view to users who are not logged in

To start with we are going to cover the following user story by the end of this step you will have an app which either displays a login view of a welcome screen dependant on whether the user is logged in or not.
User StoryDisplay a login screen to users who are not logged in when they use the app
This post doesn’t cover Auto Layout so we are going to disable it, if you are OK with Auto Layout feel free to leave it enabled and add the relevant layout constraints to the views we are about to create.
Open Main.storyboard and within the File Inspector (⌘ + ⌥ + 1)  deselect “Use Auto Layout” and “Use Size Classes” in the Interface Builder Document section.
Interface Builder Document Settings
 Drag a new View Controller onto Main.storyboard and within the Attributes Inspector (⌘ + ⌥ + 4) enter the title “Login View”. Drag aText Field onto the View and position as follows within the Size Inspector (⌘ + ⌥ + 5) and set-up the View as follows:
Login Text Field Size Attributes
Switch to the Attributes Inspector (⌘ + ⌥ + 4)  and enter the Placeholder text: “Enter a username”. Drag another Text Field onto the View and position as follows within the Size Inspector.
Password Size Attributes
Switch to the Attributes Inspector (⌘ + ⌥ + 4)  and enter the Placeholder text: “Enter a password”. Tick the Secure Text Entry checkbox.
Secure Text Entry
Drag a Button onto the View and position within the Size Inspector as follows:
Button Sizing
Double Click on the Button and change the button title to Login. Switch to the Attributes Inspector and set the Background colour as follows:
Background Button Color
Set the Text Color to White and set the Font to System Bold.
Login VIew
OK, we are now going to add a new UIViewController class for our Login View. Go to File->New->File and select Swift File. Click Next and name the file LoginViewController and click Create.
Open LoginViewController and modify as follows:
import UIKit
class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
Open Main.storyboard back up and click on the Login View and within theIdentity Inspector (⌘ + ⌥ + 3) set the Class to LoginViewController. You will also want to set the Storyboard ID to Login
Login View Custom Class
Switch to the Assistant Editor and Ctrl Click from each field to theLoginViewController
SetLoginViewFields
Name the fields as follows:
Login Field: loginTextField
Password Field: passwordTextField
Login Button: loginButton
Once done your LoginViewController should look as follows:
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var loginTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
}
view rawLoginViewController hosted with ❤ by GitHub
OK, we are now ready to show the login form. In the AppDelegate.swift file and replace application(_:didFinishLaunchingWithOptions) function with the following:

1 Comments

Previous Post Next Post