Facebook Tutorial for iOS: How To Use Facebook’s New Graph API from your iPhone App
A Facebook tutorial in which you will learn how to use Facebook’s Graph API from your iPhone app to authenticate the user, post to their wall, and more. By Ray Wenderlich.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Facebook Tutorial for iOS: How To Use Facebook’s New Graph API from your iPhone App
20 mins
If you are an iPhone developer and want to integrate Facebook into your app, things can be a bit confusing these days.
First, there’s this iPhone library called Facebook Connect that looks pretty cool – but then there’s this other thing called the Graph API too.
So what’s this Graph API thing all about, and how does it relate to Facebook Connect?
Short answer: Facebook Connect uses the old API, but the Graph API is the new API. The new Graph API is simple, has more flexibility, and you can do things with it that you couldn’t do before.
But Facebook Connect doesn’t use the Graph API, so what is a poor developer to do?
Update: Since writing this Facebook tutorial, Facebook Connect now supports the Graph API. However, this Facebook tutorial may still be useful if you want to see how things work under the hood!
That’s where this Facebook tutorial series comes in! In this three-part series, we will cover how the Graph API works step by step, including:
- How to authenticate the user with the Graph API
- How to get user information
- How to post to their wall
- How to upload photos
- And even how to add a “like button” to your Facebook fan page!
In this first article, we’ll mainly cover how to authenticate the user using the Graph API, since that’s really the hardest part (the rest is pretty simple). (Jump to Part 2 or Part 3 of the series.) So let’s get started by talking about how the authentication works!
How OAuth Authentication Works
To authenticate users to Facebook, the Graph API uses the new OAuth 2.0 protocol. Don’t worry – the name sounds imposing, but the way it works is actually pretty simple.
The idea is you make an app using the Facebook developer’s portal, and when you do you get a unique ID for your app called an API Key.
Then when you want to log a user into Facebook, you go to the following URL in a web browser:
https://graph.facebook.com/oauth/authorize? client_id=[your API key]& redirect_uri=http://www.facebook.com/connect/login_success.html& scope=[extended permissions you want]& type=user_agent& display=touch
The user will see a standard Facebook login page and they can enter in their username and password, and give any permissions required.
You don’t need to implement a redirect_uri yourself – you can just use a preset one from Facebook, as shown above. The preset callback will return to you an access token, which is what you’ll need to make all future requests.
When a user logs in, Facebooks stores some information about the login in cookies. So next time you try to login, if the cookies haven’t expired, the login will automatically complete without user intervention!
Where’s the Secret Key?
If you’re familiar with using the old Facebook Connect API, you’ll notice that nowhere in the above steps do you pass your app’s secret key.
This arguably is a security issue, but its effect is mitigated on the iPhone by the fact that Safari stores cookies on a per-app basis, and the user would probably notice if your app was trying to log in as a different app.
This is not really within the scope of this blog post so I’m not going to discuss it futher here, but if you are curious you can check out this Facebook forum post on the matter or contact me.
IMHO, on the iPhone it isn’t a huge deal so I still plan on using Facebook & the Graph API in my apps. But I am going to be very careful what I put on Facebook and what apps I allow to access it, as all of us should already know! :]
Anyway – enough background, let’s get this working in some code!
Creating a Login Dialog
The first thing we need to do is create a web view that we can redirect to the OAuth authentication URL shown above.
Since the user might not have to manually login if cookies from an old login are still valid, we will try logging in behind the scenes, and only show the web view if a manual login is required.
Let’s start by making a new project. Go to File\New Project, choose Application\View-based Application, and click “Choose…”. Name the project FBFun, and click “Save”.
Then click on File\New File, choose iPhone OS\Cocoa Touch Class\UIViewController subclass, make sure “With XIB for user interface” is checked, and click “Next”. Name the file “FBFunLoginDialog’, and click “Finish”.
Open up FBFunLoginDialog.h and replace the contents with the following:
#import <UIKit/UIKit.h>
@protocol FBFunLoginDialogDelegate
- (void)accessTokenFound:(NSString *)accessToken;
- (void)displayRequired;
- (void)closeTapped;
@end
@interface FBFunLoginDialog : UIViewController <UIWebViewDelegate> {
UIWebView *_webView;
NSString *_apiKey;
NSString *_requestedPermissions;
id <FBFunLoginDialogDelegate> _delegate;
}
@property (retain) IBOutlet UIWebView *webView;
@property (copy) NSString *apiKey;
@property (copy) NSString *requestedPermissions;
@property (assign) id <FBFunLoginDialogDelegate> delegate;
- (id)initWithAppId:(NSString *)apiKey
requestedPermissions:(NSString *)requestedPermissions
delegate:(id<FBFunLoginDialogDelegate>)delegate;
- (IBAction)closeTapped:(id)sender;
- (void)login;
- (void)logout;
-(void)checkForAccessToken:(NSString *)urlString;
-(void)checkLoginRequired:(NSString *)urlString;
@end
The first thing we do here is create a delegate, which FBFunViewController will eventually implement. We want to be able to tell this guy if we’ve found an access token or if he needs to display us on the screen.
Next, we set up a couple member variables. We need to keep track of our web view, and also store the API key and any permissions that our app wants. And of course, we need a reference to the delegate.
At the end, we just declare the methods that we’ll be implementing in our .m file later.
Ok – time to set up the UI! Open up FBFunLoginDialog.xib, drag a UIWebView to the center of the view, and resize it a bit so there’s some space at the bottom. Add a button into the bottom that says “Close”. When you’re done it should look like the following:
Then control-drag from “File’s Owner” to the UIWebView and connect it to the “webView” outlet. Also control-drag from the UIWebView back up to the “File’s Owner”, and connect it to the “delegate” outlet. Finally, control-drag from the UIButton up to “File’s Owner”, and connect it to the “closeTapped:” outlet.
That’s it with Interface Builder – save your XIB and head over to FBFunLoginDialog.m!