Integrating Facebook and Parse Tutorial: Part 1

Learn how to make an app to share photos with your Facebook friends, using Parse to easily create a back end for your app. By Toby Stephens.

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.

Integrating Parse in Your iOS App

That takes care of Facebook — now it’s time to integrate Parse into your app. Head over to http://www.parse.com/docs/downloads and download the Parse iOS SDK. In Finder, locate Parse.framework and drag it into the Frameworks section of your project.

Just as with the Facebook SDK, Parse requires a few other Frameworks and Libraries to be included in the project. Okay, admittedly, it’s more than a few. Add the following list of Frameworks and Libraries to your project’s Link Binary With Libraries:

  • AudioToolbox
  • CFNetwork
  • CoreGraphics (usually added by default)
  • CoreLocation
  • libz.1.1.3.dylib
  • MobileCoreServices
  • QuartzCore
  • StoreKit
  • SystemConfiguration

Once you’ve completed this step, your Frameworks structure should look like the following:

ts_FBParse_frameworks

Since you’re going to be using Parse throughout the app, you’ll import the Parse header in the pre-compile header, rather than in each individual class header file. Open Supporting Files\FBParse-Prefix.pch and add the following import:

#import <Parse/Parse.h>

Build and run once more to confirm that you have no compilation issues with all the included SDKs, Frameworks and Libraries. The app still doesn’t do much of anything — don’t worry, you’ll see some visible progress soon!

Building the iOS App

That was a lot of prerequisite work, but you came through with flying colors. Now it’s time to work on the code of your app.

Open AppDelegate.m and add the following two lines to the top of application:didFinishLaunchingWithOptions: method:

// Register our Parse Application.
[Parse setApplicationId:@"<your_parse_app_id>" clientKey:@"<your_parse_client_key>"];

// Initialize Parse's Facebook Utilities singleton. This uses the FacebookAppID we specified in our App bundle's plist.
[PFFacebookUtils initializeFacebook];

Be sure to replace the placeholder keys here with your actual Parse Application ID and Client Key that you got earlier when creating the app in Parse.

The above code informs your app of the existence of your Parse app and initializes the the Facebook features built in to the Parse SDK.

Add the following methods to the bottom of AppDelegate.m:

- (BOOL) application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [PFFacebookUtils handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [PFFacebookUtils handleOpenURL:url];
}

These methods are required for your app to handle the URL callbacks that are part of OAuth authentication. You simply call a helper method in PDFFacebookUtils and it takes care of the rest.

Build and run your app to confirm there are no compilation issues – your app is now linked to your Parse app!

Leveraging the Login

You’ve seen the Login screen a few times now and you’re probably itching to make it do something useful. Here’s your chance.

To keep all of the communications code in a convenient place, you’ll put the login code into a new Comms class. This class will have static methods for all of your calls to Parse and Facebook.

Create a new Objective-C class with a subclass of NSObject in your project and name the class Comms.

Open Comms.h and replace the contents with the following:

@protocol CommsDelegate <NSObject>
@optional
- (void) commsDidLogin:(BOOL)loggedIn;
@end

@interface Comms : NSObject
+ (void) login:(id<CommsDelegate>)delegate;
@end

The Comms class has a single method so far: login:. When you call this method, you will pass an object that implements the CommsDelegate protocol. When the login completes, the Comms class will call the commsDidLogin: method on the delegate object.

Now for the login method itself. Open Comms.m file and add the code below inside the @implementation:

+ (void) login:(id<CommsDelegate>)delegate
{
	// Basic User information and your friends are part of the standard permissions
	// so there is no reason to ask for additional permissions
	[PFFacebookUtils logInWithPermissions:nil block:^(PFUser *user, NSError *error) {
		// Was login successful ?
		if (!user) {
			if (!error) {
                		NSLog(@"The user cancelled the Facebook login.");
            		} else {
                		NSLog(@"An error occurred: %@", error.localizedDescription);
            		}
			
			// Callback - login failed
			if ([delegate respondsToSelector:@selector(commsDidLogin:)]) {
				[delegate commsDidLogin:NO];
			}
		} else {
			if (user.isNew) {
				NSLog(@"User signed up and logged in through Facebook!");
			} else {
				NSLog(@"User logged in through Facebook!");
			}
			
			// Callback - login successful
			if ([delegate respondsToSelector:@selector(commsDidLogin:)]) {
				[delegate commsDidLogin:YES];
			}
		}
	}];
}

The code above uses Parse’s Facebook Utils to login to Parse using Facebook credentials. You don’t need to ask for any specific Facebook permissions because the basic user information and list of friends is part of the default permissions. The code then calls the delegate method to inform the calling object of the success or failure of the logon attempt.

The methods in your Comms class should to be accessible from anywhere in the app, so it makes sense to put the Comms class header import into the pre-compile.

Open Supporting Files\FBParse-Prefix.pch and add the following import:

#import "Comms.h"

Now you need to call your new login method from the Facebook login button on the login view controller. Open FBLoginViewController.m and add the following code to loginPressed:

// Disable the Login button to prevent multiple touches
[_btnLogin setEnabled:NO];
	
// Show an activity indicator
[_activityLogin startAnimating];
	
// Do the login
[Comms login:self];

The method is referenced in your storyboard, to the touch-up-inside event on the Facebook login button. When the button is pressed, you disable the Facebook login button so that you don’t get any trigger-happy users attempts to hit the button multiple times. Next, you display an activity indicator to inform the user that something is happening behind the scenes. Finally, you call your new login: method that you added to the Comms class.

The only thing left to do is make FBLoginViewController conform to the CommsDelegate protocol so that it can be informed about Comms actions.

Still in the FBLoginViewController.m file, add the CommsDelegate protocol to the class extension as so:

@interface FBLoginViewController () <CommsDelegate>

Then implement the required delegate method as follows:

- (void) commsDidLogin:(BOOL)loggedIn {
	// Re-enable the Login button
	[_btnLogin setEnabled:YES];
	
	// Stop the activity indicator
	[_activityLogin stopAnimating];

	// Did we login successfully ?
	if (loggedIn) {
		// Seque to the Image Wall
		[self performSegueWithIdentifier:@"LoginSuccessful" sender:self];
	} else {
		// Show error alert
		[[[UIAlertView alloc] initWithTitle:@"Login Failed"
					    message:@"Facebook Login failed. Please try again"
					   delegate:nil
				  cancelButtonTitle:@"Ok"
				  otherButtonTitles:nil] show];
	}
}

The above method is your callback from the Comms class. First, the method does a bit of cleanup by re-enabling the Login button and hiding the activity indicator. Then, on a successful login, it performs a segue to the next view controller. However, if the login attempt failed, it displays an alert to the user.

Build and run your project, and behold as your app asks for permission to access your basic Facebook account details:

ts_FBParse_permissions

Choose OK, and if authentication succeeds the app will automatically transition to the image wall:

ImageWall

Also, if you check the console you will see that the login was successful:

FBParse[1727:907] User signed up and logged in through Facebook!

The Parse PFFacebookUtils class makes use of the three Facebook authentication methods available on iOS devices. First, it tries to use the native Facebook app. If the Facebook app is not installed on the device, it attempts to use the Facebook account set up in the operating system on iOS 6 and above. Finally, if neither of these options are available, it falls back on the basic Facebook web dialogs.

Note:
Toby Stephens

Contributors

Toby Stephens

Author

Over 300 content creators. Join our team.