Parse Tutorial: Getting Started with Web Backends

Get started with Parse, and learn how to set up your iOS app with a backend that lets you store user accounts, posts, and attachments! By Ron Kliffer.

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 5 of this article. Click here to view the first page.

Creating Some Sample Objects

Every object you upload to Parse becomes an entry in the database scheme that you defined for your app. Think of these objects as being somewhat like dictionaries – you store data in them identified by key, then you can retrieve your data with those same keys later on.

In this example, you’ll upload an object called “Player”, with “Name” and “Score” as fields. So in your database, you will have a table called “Player” with all the objects uploaded with that name. You’ll see this with the example calls below.

Open AppDelegate.swift, and add the lines below to application(_:didFinishLaunchingWithOptions:) just above return true:

     
let player = PFObject(className: "Player")
player.setObject("John", forKey: "Name")
player.setObject(1230, forKey: "Score")
player.saveInBackgroundWithBlock { (succeeded, error) -> Void in
  if succeeded {
    println("Object Uploaded")
  } else {
    println("Error: \(error) \(error.userInfo!)")
  }
}

As you can see here, you are using asynchronous mode to upload the object, and you are checking the result in a closure.

PFObject is a base class providing basic object manipulation methods. The best part is you don’t need to create a table in the Parse web interface itself – it will automatically create a schema for you based on what you upload.

Build and run! If you put your API keys into the code properly, and your app properly registered with the Parse service, then everything should run without issue, and you will see the message “Object Uploaded” appear in the console. If something went wrong, then you’ll see an error message instead.

But where did your object go? Is it just out there floating in cyberspace?

To check that you saved your object correctly, go to your Parse dashboard, click on Core, where you should see the object, as below:

Parse08

Congratulations, you’ve successfully communicated with the back end! :]

Note: If you did see an error message such as “The network connection was lost,” and you’re running on the iOS simulator, try restarting the simulator – useful advice for when other network errors occur as well :]

Also, if you get the “Object Uploaded” message, but you don’t see any data in the Parse dashboard, try reloading the dashboard page and/or click the refresh button in the upper right of the dashboard.

Before continuing to the next section create two more records. Leave the name as “John,” but change the score to 810, and run the app. Now you have two records with name “John” but differing scores. Now change the name to “Sally” and the score 2400 and run the app to create a third record.

Retrieving Objects

Now, it’s time to retrieve the objects. For this purpose, Parse has the class PFQuery – unsurprisingly, it performs queries, as noted in the PFQuery documentation.

You will code a query for all the objects with a score greater than 1000 where “Name” is equal to “John”. Comment out (or delete) the previous code or you will be uploading a new object every time. In its place, put the following code:

// 1
let query = PFQuery(className: "Player")
// 2
query.whereKey("Name", equalTo: "John") 
query.whereKey("Score", greaterThan: 1000)
// 3
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in 
  if error == nil {
    println("Successfully retrieved: \(objects)")
  } else {
    println("Error: \(error) \(error.userInfo!)")
  }
}
  1. Here you create the query object, the name will be the name of the table where you want to look.
  2. You are only going to get those objects where the name is “John” and where the score is bigger than 1000.
  3. Send the query, and print the result in a closure.

Build and run your app. Once again, the operation is asynchronous and does not stop your UI from appearing quickly — this is key to keeping your users happy. :] In the console, you should see all of the objects that match the query, as shown in the screenshot below:

Parse09

After this brief exploration of basic storage and query operations, you can continue working in the real project.

Comment out (or delete) these lines from application(_:didFinishLaunchingWithOptions:) before continuing.

User Registration

The first step that your users will encounter in your app is to register as a user.

Open the file RegisterViewController.swift; right now the view doesn’t do anything apart from being opened and closed. Your mission is to implement the functionality for user registration when the user taps the “Sign Up” button.

Locate the action method signUpPressed(_:): and replace it with the following code:

@IBAction func signUpPressed(sender: AnyObject) {
  //1
  let user = PFUser()

  //2
  user.username = userTextField.text
  user.password = passwordTextField.text
        
  //3
  user.signUpInBackgroundWithBlock { succeeded, error in
    if (succeeded) {
      //The registration was successful, go to the wall
      self.performSegueWithIdentifier(self.scrollViewWallSegue, sender: nil)
    } else if let error = error {
      //Something bad has occurred
      self.showErrorView(error)
    }
  }
}

In the code above, the steps followed for creating a user are:

  1. Create a new PFUser object named user. You will use this object for both the login and register processes. It stores your authenticated user, so you can access the data for this user any time you want.
    You can find the PFUser class documentation here.
  2. Assign the username and password to user from the text fields in the view.
  3. Call the method that registers the user in the background, and checks the response in a closure. There are two possible responses here: either the response is okay and you logged in your newly created user, or there was an error. In the first case, move on to the wall view, and otherwise show the user a description of the error.

Build and run the app to check for errors. To check the user registration process, run the app, and at the Log In screen, press the Sign Up button. You should see the following:

Initial Screenshot

Enter the name and password of the new user, and press the Sign Up button. If all goes well the app will move to the wall view.

Great! But you still need to verify that the code actually saved the new user in your schema! You can check that you successfully created your new user by looking in the User section of Parse’s Core data browser for the backend project, as shown below:

Parse11

Congratulations! You created your first user! Now it’s time to let that user log in and get busy with the backend! :]