Basic user registration with Swift

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

 

showcase_app

 

In order to continue with this tutorial, you should setup your project properly, as described in the Quickstart:

Quickstart

Once the project is setup and the Parse SDK is working properly, you should continue with the next step.

Step 1 – The login function

Creating a login function with back4app is amazingly simple. It is sufficient to use the following code:

PFUser.logInWithUsername(inBackground: username_here, password: password_here, 
block: {(user, error) -> Void in
    if let error = error as NSError
        let errorString = error.userInfo["error"] as? NSString
        // In case something went wrong... 
    }
    else {
        // Everything went alright here
    }
})

This code should be added to the element of your app that does the login, as the values described in the code should be changed accordingly. The next step describes the register function.

Step 2 – The register function

Equally simple is the function to register the client, which is shown below:

// Defining the user object
let user = PFUser()
user.username = "username_here"
user.password = "password_here"
user.email = "email_here"
        
// 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, use errorString to get the error
     } else {
         // Everything went okay
     }
}

Which should be put in whatever element triggers the registering mechanism. The next step integrates both functions to the app that is going to be built.

Step 3 – Integrating the code to the app

Start out by creating two labels, two buttons and two text fields, as well as setting up their style. As these elements have been set, we should append objects in the code to represent the text fields and add functions to be triggered as soon as the buttons are pressed. To do so, you should click on the element you want to add the event, then hold Control and drag the element to the code you want to add, as shown below for the login button:

 

app_connect_swift

 

As well as connect the text fields to the app, shown below for the login text field:

 

app_connect_outlet_swift

 

Now we add the code to each section of the buttons, noting that we will alert to the user if the login was successful or the registration was done. The resulting code is in the github repository:

https://github.com/rvitorper/back4app-user-swift