How To Easily Create A Web Backend for Your Apps with Parse

This is a post by Tutorial Team Member Antonio Martínez, a mobile software developer currently working as an iOS Developer in London. In my previous article, you learned about some of the backend service providers available today and what types of features you can expect from them. Now it’s time to start working with one […] By .

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

Creating Some Sample Objects

Now that your project is configured and connected with Parse, take a minute to go over the following concepts about sending and retrieving objects from the backend.

You can create a new project for this, by following the steps that you used previously, or you can alternately use the AppDelegate in the base project.

In this example, you will use the class PFObject, which is a base class providing basic object manipulation methods. You can read more about PFObject here:

https://parse.com/docs/ios/api/Classes/PFObject.html

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

In this example, you will 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.

Go to didFinishLaunchWithOptions: and right after connecting to the parse service, add these lines:

PFObject *player = [PFObject objectWithClassName:@"Player"];//1
[player setObject:@"John" forKey:@"Name"];
[player setObject:[NSNumber numberWithInt:1230] forKey:@"Score"];//2
[player save];//3
  1. In this line you create the object and give the object a class name of “Player”.
  2. Here you assign the values to the fields. Your player has a name of “John” and a score of “1230”.
  3. Here you save the object. This will send the object to the server in synchronous mode.

And that’s it! 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 your app! If you put your keys into the code properly, and your app properly registered with the Parse service before the object is added, then everything should run without issue.

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

To check that your object was saved correctly, go to your Parse dashboard, click on “Data Browser”, where you should see the object, as below:

This is the easiest way of saving an object. Congratulations, you’ve successfully communicated with the back end! :]

Going Asynchronous

But as you may have noticed, there was a warning message in the console. Your app is blocked until the object is completely sent, as this is a synchronous network operation! Not only can you not check the result of the call, your user is stuck waiting for it to complete with an unresponsive API.

That wouId give you an instant 1-star rating! :[ Of course, there is a way to fix both of these problems.

Comment out the previous code in didFinishLaunchWithOptions:; otherwise, your app will upload a new object every time you run. Add the following code instead:

     PFObject *anotherPlayer = [PFObject objectWithClassName:@"Player"];
    [anotherPlayer setObject:@"Jack" forKey:@"Name"];
    [anotherPlayer setObject:[NSNumber numberWithInt:840] forKey:@"Score"];
    [anotherPlayer saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded){
            NSLog(@"Object Uploaded!");
        }
        else{
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            NSLog(@"Error: %@", errorString);
        }
    
    }];

As you can see here, you are using asynchronous mode to upload the object, and you are checking the result in a block. You should be familiar with blocks by now as they are becoming more and more common in iOS; even simple UIView animations are done in blocks now. Fortunately, there’s a great tutorial site where you can refresh your memory about important language features like this – right here! :] Take a look at How To Use Blocks in iOS 5 Tutorial – Part 1.

Build and run your app!

Check the Parse Dashboard to see if your object was correctly sent to the server. The difference this time is that your app is not blocked while the object is being uploaded to the backend.

You should notice that the network activity indicator in the device (or simulator) appears and the login screen pops up while it spins. A short time later, once communications are complete, you will see the NSLog message appear in the console. This will prove to be really useful when uploading images, which take much longer to transfer.

Like before, go to the Data Browser and you will see the object transferred asynchronously alongside the first object which was transferred synchronously.

Hey Everyone, Come Back! – 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 be coding a query for all the objects with a score greater than 1000 where “Name” is equal to “John”. As before, comment out the previous code or you will be uploading a new object every time. In its place, put the following code:

PFQuery *query = [PFQuery queryWithClassName:@"Player"]; //1
[query whereKey:@"Name" equalTo:@"John"];//2
[query whereKey:@"Score" greaterThan:[NSNumber numberWithInt:1000]]; //3
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {//4
    if (!error) {
        NSLog(@"Successfully retrieved: %@", objects);
    } else {
        NSString *errorString = [[error userInfo] objectForKey:@"error"];
        NSLog(@"Error: %@", errorString);
    }
}];
  1. Here you create they query object, the name will be the name of the table where you want to look.
  2. You are only going to get the objects which name is “John”…
  3. …and where the score is bigger than 1000
  4. Send the query, and print the result in a block.

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:

Screen Shot 2012 11 10 at 9 48 56 PM

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

Go back to the base project if you were working on the other project, or comment out these lines in case you were working in the main project.

Sign on the Dotted Line — User Registration

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

Open the class RegisterViewController.m in the base project. Add the Parse header as below:

#import <Parse/Parse.h>

As you can see, 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 touches the “Sign Up” button.

For this purpose, you can find this IBAction connected to that button:

//Sign Up Button pressed
-(IBAction)signUpUserPressed:(id)sender
{
    //TODO
    //If signup sucessful:
    //[self performSegueWithIdentifier:@"SignupSuccesful" sender:self];
}

As you can see, you will need to add the code that will register a user, and check if the registration was successful.

Replace the content of the above method with the following code:

//Sign Up Button pressed
-(IBAction)signUpUserPressed:(id)sender
{
    //1
    PFUser *user = [PFUser user];
    //2
    user.username = self.userRegisterTextField.text;
    user.password = self.passwordRegisterTextField.text;
    //3
    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            //The registration was successful, go to the wall
            [self performSegueWithIdentifier:@"SignupSuccesful" sender:self];
            
        } else {
            //Something bad has occurred
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [errorAlertView show];
        }
    }];
}

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

  1. Create a new object PFUser. This class will be used for login and register processes. It will store your authenticated user, so you can access the data for this user any time you want.
    You can find the documentation about the PFUser class here.
  2. Assign the username and password to the user object from the TextFields in the view.
  3. Call the method that will register the user in background, and check the response in a block. There’s two possible responses here: the response is ok; and your user is created and logged, so move to the wall view. Or, there was an error, and you can show the user a description of the error.

Build and run the app and 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:

Enter the name and password of the new user, and press the Sign Up button. If everything went well, and no errors were received by the registration process, the app will move to the wall view.

Great! But you still need to verify that your new user actually was saved in your schema! You can check that your user was successfully created by looking in the Parse data browser of the backend project, as below:

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