Facebook Tutorial for iOS: How To Get a User Profile with Facebook’s New Graph API from your iPhone App

A Facebook tutorial for iOS that teaches you how to get a user profile with Facebook’s new Graph API from your iPhone app. By Ray Wenderlich.

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

Integrating Pictures

We’re going to need some picture of babes and dudes to show. You can use your own, or grab these images. Once you have them downloaded, drag them into your resource group. When the dialog pops up, verify that “Copy items into destination group’s folder (if needed)” is checked, and click “Add”.

Requesting the User’s Profile

Phew! Finally, we’re ready to write some code.

The first thing we’ll need to do is figure out if you like babes, or if you like dudes. And believe it or not – you can find that out via your Facebook profile! :]

So first let’s add the headers we need and the declarations for our variables:

// Add to the top of the file
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSON.h"

// In synthesize section
@synthesize textView = _textView;
@synthesize imageView = _imageView;
@synthesize segControl = _segControl;
@synthesize webView = _webView;
@synthesize accessToken = _accessToken;

// In dealloc
self.textView = nil;
self.imageView = nil;
self.segControl = nil;
self.webView = nil;
self.accessToken = nil;

Nothing fancy here. Next comes the call to get the user’s Facebook profile information:

- (void)getFacebookProfile {
    NSString *urlString = [NSString 
        stringWithFormat:@"https://graph.facebook.com/me?access_token=%@", 
        [_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURL *url = [NSURL URLWithString:urlString];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDidFinishSelector:@selector(getFacebookProfileFinished:)];
    
    [request setDelegate:self];
    [request startAsynchronous];
}

- (void)rateTapped:(id)sender {
    
}

The first thing we do is create a string for the Graph API object that we wish to get. In this case, we want the current user’s profile, which we can access at http://graph.facebook.com/me.

However, we need to pass in the access token as well. We do this by simply appending it at the end of the URL as an HTTP get parameter. Remember we need to escape the access token with percent escapes for the URL.

Next, we send out the actual request. Instead of using NSURLRequest / NSURLConnection, we make use of ASIHTTPRequest here. This simplifies things a bit for us by managing storing the NSData for us along the way, and just giving us a callback when we’re done.

We use an override to specify the selector we want to be called when it’s finished (rather than accepting the default), this way we can have different callbacks for different requests we make. We also set ourselves as the delegate.

Notice we’re using the asynchronous method – using synchronous methods in an iPhone app is generally a no-no, as it makes the app unresponsive!

Parsing the Response from Facebook

Next add the callback for when we receive the data back from Facebook:

- (void)getFacebookProfileFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *responseString = [request responseString];
    NSLog(@"Got Facebook Profile: %@", responseString);
    
    NSString *likesString;
    NSMutableDictionary *responseJSON = [responseString JSONValue];   
    NSArray *interestedIn = [responseJSON objectForKey:@"interested_in"];
    if (interestedIn != nil) {
        NSString *firstInterest = [interestedIn objectAtIndex:0];
        if ([firstInterest compare:@"male"] == 0) {
            [_imageView setImage:[UIImage imageNamed:@"depp.jpg"]];
            likesString = @"dudes";
        } else if ([firstInterest compare:@"female"] == 0) {
            [_imageView setImage:[UIImage imageNamed:@"angelina.jpg"]];
            likesString = @"babes";
        }        
    } else {
        [_imageView setImage:[UIImage imageNamed:@"maltese.jpg"]];
        likesString = @"puppies";
    }
    
    NSString *username;
    NSString *firstName = [responseJSON objectForKey:@"first_name"];
    NSString *lastName = [responseJSON objectForKey:@"last_name"];
    if (firstName && lastName) {
        username = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
    } else {
        username = @"mysterious user";
    }
    
    _textView.text = [NSString stringWithFormat:
        @"Hi %@!  I noticed you like %@, so tell me if you think this pic is hot or not!",
        username, likesString];
    
    [self refresh];    
}

This method looks long, but it’s actually pretty simple.

We first convert the string we got back from the server into Objective-C objects using the JSON parser. We then look for the interested_in variable to tell if you like babes or dudes.

Based on your interest, we set the image appropriately. If it’s not there, we just set you as liking puppies (because who doesn’t like puppies?!)

Then we get your first and last name, and create a customized message for you.

One last thing: we need to modify the accessTokenFound method to start the ball rolling:

- (void)accessTokenFound:(NSString *)accessToken {
    NSLog(@"Access token found: %@", accessToken);
    self.accessToken = accessToken;
    _loginState = LoginStateLoggedIn;
    [self dismissModalViewControllerAnimated:YES];    
    [self getFacebookProfile];        
    [self refresh];
}

And that’s it! Compile and run the app, and if all works you should see something like the following:

Hot or Not Message

Where To Go From Here?

Here is a sample project with all of the code we developed in the above Facebook tutorial.

If you’re wondering what other cool stuff you can find on a user’s profile page – check out the Facebook Graph API Reference for User.

You can also get a ton of other information in a similar manner to how we got the user’s profile. With the knowledge you have here, check out the Graph API reference and see what else you can snag!

In the next Facebook tutorial in the series, we take this a step further and show you how to post to a user’s wall, upload photos, and integrate a “like button” for your Facebook fan page!

Please comment below with any comments or questions you may have… and also if you like babes or dudes. :]