The Conversation

iPhone, Facebook, oAuth 2.0 and the Graph API. A Tutorial.

by Dominic Dimarco
published 05/25/10

categorized as: Technology
tags: , , , , ,

NOTE: The source code for this tutorial is still linked below, however the FULL Facebook/iPhone Graph API can be found here:  http://github.com/reallylongaddress/iPhone-Facebook-Graph-API


The new Facebook Graph API looks to be the cat’s meow, the bee’s knees, the coolest thing since sliced bread. Ok, that’s a bit much… but it is a whole lot more powerful, easier and cross-platform consistent than the previous plethora of Facebook APIs.  The Graph API was announced at Facebook’s F8 conference just over a month ago.  At the time of release, I was surprised no iPhone SDK was made available. I fully expected that at least an unofficial SDK as well as full blown tutorials would be out en-mass by now, but to no avail.

Not nearly patient enough to wait for an official SDK or iPhone API from Facebook, I asked Google how to “Facebook oAuth 2.0 iPhone” and was disappointed with the results. It turns out, there are very few, woefully incomplete examples of how to authenticate to Facebook via oAuth 2.0, from an Objective-C / native iPhone application. The best implementation I found was a pseudo API, however I don’t care for it since it uses the old Facebook Connect authentication scheme, then implements the graph API on top of that layer.

Adding insult to injury, there was lots of news last week about the Android Graph API but no love for the iPhone:

“Facebook’s mobile development team soft launched a Facebook SDK for Android, bringing functionality that was previously only available on the iPhone to the Android platform. It gets better: Facebook gave the Android platform a de facto exclusive on two of its newest initiatives: Open Graph APIs and OAuth 2.0.”

Will M, Allfacebook.com

Aside:  My theory on why there’s not iPhone/Objective-C API is:  That functionality is going to be directly (and deeply) integrated in the forthcoming iPhone OS 4.0 (June?).

All of that being said, I slashed, burned and figured it out.  Here’s the result, a very simple end-to-end example of how to connect to Facebook via oAuth 2.0 on the iPhone.

Part 1: Connecting to Facebook with oAuth 2.0 on the iPhone

Part 2 of this series will cover how to interact with the Graph API.

NOTE: You can go to http://graph.facebook.com to play with the Graph API, directly in your browser.

Assumptions and requirements:

  • Facebook: You’ve installed the Facebook Developer Application.
  • iPhone: You’ve installed the iPhone Xcode SDK installed (I believe most any version will work) and have a some level of knowledge about objective-C, Interface Builder, etc.

Facebook Setup

  • Go to the Facebook developer App and install if you haven’t already
  • Once you’ve installed Setup a New Application
  • Next you need to configure a few app settings:
    • BASIC tab: enter an Application Name
    • AUTHENTICATION tab: un-check and leave everything blank
  • Save changes.  Save yourself some frustration and make note of the Application ID now.

Sample Code:

Facebook/iPhone/oAuth

iPhone Setup

Open up the Xcode project. There’s only 2 functions at play here:

viewDidLoad

This function is called as soon as the view has completely loaded.  It then asks the UIWebView to begin the oAuth 2.0 authorization process by sending a request to:

https://graph.facebook.com/oauth/authorize?client_id=your_facebook_app_id&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=touch

(NOTE:  display=touch, we’ll get back to this in a bit)

webViewDidFinishLoad

This function is called several times throughout the login process execution. These multiple web view finished calls have to do with server redirects within the oAuth 2.0 process flow. We’re only interested when the requested URL contains:

access_token=

And the associated obj-c code to identify when this occurs is:

NSRange access_token_range = [url_string rangeOfString:@"access_token="];
if (access_token_range.length > 0) {

Then, this code extracts the oAuth token out of the URL we received back the Facebook oAuth servers:

int from_index = access_token_range.location + access_token_range.length;
NSString *access_token = [url_string substringFromIndex:from_index];

iPhone Configuration

In oAuth2TestViewController.m update the client_id variable with your Facebook Application ID:

/*Facebook Application ID*/
NSString *client_id = @"YOUR_FB_APPLICATION_ID";

Running the App

Once you’ve pasted your Facebook Application ID into the right place, you should be able to run the application straight away.

When you first launch the simulator oAuth2TestViewController it will automagically initialize the oAuth login procedure via the webView object. Barring any errors or configuration issues, you should get a Facebook login screen optimized for an iTouch device (NOTE:  thus the display=touch we made note of above). Finally after you’ve logged in you’ll see your oAuth access token in the Xcode debug console.

Sample Code:

Facebook/iPhone/oAuth

That’s it. No bells & whistles, no buttons, no Interface Builder, no UITableViewControllers; just the bare minimum required to get an oAuth 2.0 token via an itouch device from Facebook.

In part 2, we’ll interact with the Graph GETing from and POSTing data to it, using a pseudo-API.

Find me here: @dominicdimarco

NOTE: (5/27/2010 11:09 AM MST) The original post has been updated incorporating feedback from comments below.



Similar Posts

What people are saying

Respond


  • by Cory D. Wiles
    on Jun 11, 2010

    Reply

    I blogged about this exact topic. Facebook sucks for not having released an update to their iPhone SDK

    http://blog.corywiles.com/facebook-graph-api-with-a-native-iphone-appli

  • by Minar
    on Jun 19, 2010

    Reply

    I appreciate your tutorial.
    I want to post images/messages to my news feed using the graph api. The documentations says that I need to use
    curl -F ‘access_token=…’ \
    -F ‘message=Hello, Arjun. I like this new API.’ \
    https://graph.facebook.com/arjun/feed

    Is there a way of doing this using NSURLRequest?

    ——————–
    6/22/2010 Part 2 of this series will be released on 6/29. With that post I’ll show off a pseudo API with the ability to upload files from your iPhone to Facebook using a NSMutableURLRequest.

    Dominic

  • by Kiran
    on Jun 29, 2010

    Reply

    Thank you for this code!

    It worked great the first few times for me. Then I changed users a few times and now I’m seeing some odd results.

    Previously, I was getting “normal” access tokens. Now, I see things like:

    125043510846930|2.n1N6v_oIUWQsIZXmwoD2MQ__.8….(etc)

    The problem is that this statement breaks the functionality:

    ——————-
    FbGraph.m line 237:

    //finally we want to remove anything that occurs after a ‘.’
    NSRange period_range = [access_token rangeOfString:@"."];
    ——————-

    My access token is now “125043510846930|2.”, which causes the oAuth exception: “Invalid access token signature.”

    Any help in getting past this would be greatly appreciated.

    Thanks!

    • by Dominic Dimarco
      on Jun 30, 2010

      Reply

      Nice catch. I’ve fixed the bug and re-uploaded the xcode project to this post: iPhone, Facebook, oAuth 2.0 and the Graph API. A Tutorial, Part 2.

      Else you can ‘patch’ the project you have, by removing the two lines you reference above and replace with:

      //remove everything ‘&’ (inclusive) onward…
      NSRange period_range = [access_token rangeOfString:@"&"];

      //move beyond the .
      access_token = [access_token substringToIndex:period_range.location];

      Thanks,
      Dominic

  • by David Peterson
    on Jul 02, 2010

    Reply

    Thanks for the excellent set of posts! This info is hard to come by on the Web.

    I downloaded your Xcode project, but when I run it I get a blank screen. No errors, just a white screen. Has there been some changes to the way facebook uses their API?

    Cheers,

    David

Link Love