Basic User Registration with Email Verification – Swift

After this tutorial, you’ll be able to build a user system like this one:

 

app_working_email

 

Before going into the action, make sure you have a working project and know how to use the login and register functionalities of the back4app’s Parse API. You can check out the links below to the Quickstart and the Basic User Registration:

Quickstart

Basic user registration with Swift

Step 1 – Enable Email verification

To enable the Email verification, just go to your Back4app App page and find this option:

 

Screen Shot 2016-08-25 at 3.16.31 PM

 

Click to see more options and tick a checkbox just like this one:

 

Screen Shot 2016-08-25 at 3.16.37 PM

 

You are all set with the email verification on the server! Now, to the code.

Step 2 – Implementing the register function

To illustrate the functionality, we are going to implement a similar version of the Basic User Registration app. The key difference here is that the username is the user’s email, which simplifies a lot the login-registration mechanics. Hence, our register function will be as follows:

Note: key changes have been highlighted

// Retrieving the info that is relevant
let email = email_here
let password = password_here

// Defining the user object
let user = PFUser()
user.username = email
user.password = password
user.email = email

// Signing up using the Parse API
user.signUpInBackground {
    (success, error) -> Void in
        if let error = error as NSError? {
            let errorString = error.userInfo["error"] as? NSString
            // In case something went wrong...
        } else {
            // Everything went ok
        }
}

We don’t have to check the email address format. Back4App does that for you. Now to the login part.

Step 3 – Implementing the login function

The additional step that has to be implemented in the login function is to check if the email has been verified. This has to be added on the success section of the code, shown below:

Note: Key changes have been highlighted

// Retrieving the info that will be used
let email = email_here
let password = password_here

// Defining the user object
PFUser.logInWithUsername(inBackground: email!, password: password!, block: {(user, error) -> Void in
    if let error = error as NSError? {
        let errorString = error.userInfo["error"] as? NSString
        // Something went wrong
    }
    else {
        // Still need to check if the email has been verified
        let emailVerified = user?["emailVerified"];
        if emailVerified as! Bool == true {
            // Everything is fine
        }
        else {
            // The email has not been verified, so logout the user
            PFUser.logOut()
        }
    }
})

The full source code to the project is in the link below:

http://github.com/rvitorper/back4app-email-swift