iOS

Login and User registration tutorial using Swift

Introduction

This section explains how you can create an app with a simple user registration using Parse Server core features through Back4App.

At any time, you can access the complete iOS Project built with this tutorial at our GitHub repository.

Prerequisites

To complete this tutorial, you need:

Let’s get started!

Following the next steps you will be able to build an App that will Sign-in, Sign-up and Logout at Back4App Database.

Step 1 - Set up and Create your Sign Up and Login UI

  1. Go to Xcode, access the main folder from the Project and then open the ViewController.swift file to edit it.

  2. In ViewController.swift make sure to include the Parse module by including it at the top of the file.
    1
    
    import Parse
    
  3. Go to Main.storyboard, drag four UITextFields onto the ViewController in the main storyboard. Center the textfield and put two at the top and two at the bottom of the view controller. Drag two more UIButtons on to the view and place them below the textfields. Drag one more Loader Indicators on each Button.
    Set the top button text to say Sign In. Set the bottom bottom to say Sign Up. Set the text fields to say username and password.

  4. Next we are going to connect your UITextFields in your storyboard to properties in your view controller. Add the following properties to the top of ViewController.swift. Next go to your storyboard and right click on each UITextField and click on the reference outlet then drag a line back to the ViewController icon and set it to the appropriate field. signInUsernameField connects to the sign In Username Field, etc…

It should look like this:

App working in Back4App!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import UIKit
import Parse

class ViewController: UIViewController {

    @IBOutlet weak var txtUsernameSignin: UITextField!
    @IBOutlet weak var txtPasswordSignin: UITextField!
    @IBOutlet weak var indicatorLogin: UIActivityIndicatorView!
    
    @IBOutlet weak var txtUsernameSignup: UITextField!
    @IBOutlet weak var txtPasswordSignup: UITextField!
    @IBOutlet weak var indicatorSignup: UIActivityIndicatorView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    @IBAction func signin(_ sender: Any) {
        //todo
    }
    
    @IBAction func signup(_ sender: Any) {
        //todo
    }

}

Step 2 - Create a Sign-in function

Add the following code inside the sign-in function:

1
2
3
4
5
6
7
8
9
10
    @IBAction func signin(_ sender: Any) {
        PFUser.logInWithUsername(inBackground: self.txtUsernameSignin.text!, password: self.txtPasswordSignin.text!) {
          (user: PFUser?, error: Error?) -> Void in
          if user != nil {
            self.displayAlert(withTitle: "Login Successful", message: "")
          } else {
            self.displayAlert(withTitle: "Error", message: error!.localizedDescription)
          }
        }
    }

Step 3 - Create a Sign-up function

Add the following code inside the sign-up function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    @IBAction func signup(_ sender: Any) {
        let user = PFUser()
        user.username = self.txtUsernameSignup.text
        user.password = self.txtPasswordSignup.text
        
        self.indicatorSignup.startAnimating()
        user.signUpInBackground {(succeeded: Bool, error: Error?) -> Void in
            self.indicatorSignup.stopAnimating()
            if let error = error {
                self.displayAlert(withTitle: "Error", message: error.localizedDescription)
            } else {
                self.displayAlert(withTitle: "Success", message: "Account has been successfully created")
            }
        }
    }

Step 4 - Log Out

When logging, it creates a Session object, which points to the User logged in. If login is successful, ParseUser.CurrentUser() returns a User object, and a Session object is created in the Dashboard. Otherwise, if the target username does not exist, or the password is wrong, it returns null.

To do Logout follow the steps below:

  1. Go to Main.storyboard, drag one UIButton called “Logout”, and add a action between this UIbutton and the ViewController.swift.

  2. Add the following code in this function:

    1
    2
    3
    
     @IBAction func logout(_ sender: Any) {
         PFUser.logOut()
     }
    

Step 5 - Application Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import UIKit
import Parse

class ViewController: UIViewController {
    
    @IBOutlet weak var txtUsernameSignin: UITextField!
    @IBOutlet weak var txtPasswordSignin: UITextField!
    @IBOutlet weak var indicatorSignin: UIActivityIndicatorView!
    
    @IBOutlet weak var txtUsernameSignup: UITextField!
    @IBOutlet weak var txtPasswordSignup: UITextField!
    @IBOutlet weak var indicatorSignup: UIActivityIndicatorView!
    
    @IBOutlet weak var btnLogout: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func signin(_ sender: Any) {
        PFUser.logInWithUsername(inBackground: self.txtUsernameSignin.text!, password: self.txtPasswordSignin.text!) {
          (user: PFUser?, error: Error?) -> Void in
          if user != nil {
            self.displayAlert(withTitle: "Login Successful", message: "")
          } else {
            self.displayAlert(withTitle: "Error", message: error!.localizedDescription)
          }
        }
    }
    
    @IBAction func signup(_ sender: Any) {
        let user = PFUser()
        user.username = self.txtUsernameSignup.text
        user.password = self.txtPasswordSignup.text
        
        self.indicatorSignup.startAnimating()
        user.signUpInBackground {(succeeded: Bool, error: Error?) -> Void in
            self.indicatorSignup.stopAnimating()
            if let error = error {
                self.displayAlert(withTitle: "Error", message: error.localizedDescription)
            } else {
                self.displayAlert(withTitle: "Success", message: "Account has been successfully created")
            }
        }
    }
    
    @IBAction func logout(_ sender: Any) {
        PFUser.logOut()
    }
    
    func displayAlert(withTitle title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default)
        alert.addAction(okAction)
        self.present(alert, animated: true)
    }
    
}

The application UI will be similar to this:

Step 6 - Test your app

  1. Run your app and create a couple of users, also try logging in again after registering them.
  2. Login at Back4App Website.
  3. Find your app and click on Dashboard > Core > Browser > User.
  4. Try logging in and out with the same user and signing back in.

At this point, you should see your users as displayed below:

Parse Dashboard

Note: Using the codes displayed above, every time you log in with a user, a Session is opened in your Dashboard, but when the user logs out that particular Session ends. Also, whenever an unsuccessful login or sign up attempt occurs, the Session opened in Parse Server Dashboard is deleted.

It’s done!

At this stage, you can log in, register or log out of your app using Parse Server core features through Back4App!