Resources : Blog

iPhone FBConnect: Facebook Connect Tutorial

By Sourabh Shroff in iPhone - iPad

February 20, 2010

< All >

Update (27 June 2012) : You can find the latest updated facebook integration tutorial on our blog at: Facebook iOS SDK Tutorial : iPhone App Facebook integration with SSO (Single Sign On)

Please note that this tutorial is now obsolete. Please use facebook’s official tutorial

Now a days social networking websites like facebook are becoming very popular, so integrating facebook with app has become a necessity to make you application popular. We are going to do the same through this tutorial. The Facebook Connect SDK provides code which third-party developers can embed into their applications to connect to their Facebook accounts and exchange information with iPhone apps. It’s a way of embedding “social context” to an iPhone app, according to Facebook.

Create a Viewbased Application with name ‘FacebookAPI’.

Prerequisite:
1.Download Facebook Connect for iPhone SDK (http://svn.facebook.com/svnroot/platform/clients/packages/fbconnect-iphone.zip) or you can download same from here
Just go through the project. In particular, the “Connect” sample project. Sample Project gives demo of some of the functionality.

1.1.Open src/FBConnect.xcodeproj from SDK that you downloaded, and your own project as well.

1.2.Drag n drop FBConnect group. Make sure “Copy items into destination group folder” is NOT checked. It should look as shown below

iPhone FBConnect: Facebook Connect Tutorial

1.3.Go to Project Menu ->Edit project settings and scroll down to “User Header Search Path” add entry which will point to “src folder”

iPhone FBConnect: Facebook Connect Tutorial

1.4.To test import all .m n .h files in case any miss. And compile.

2.Login to Facebook. After that go to Developers Page (http://www.facebook.com/developers/) as shown below.

iPhone FBConnect: Facebook Connect Tutorial

3.Register your application with Facebook

3.1.Click on Set up New Application Button in the upper right hand corner.

3.2.Give Application name and click on create application button. Then you will see new application screen with detail including “API key”and “API Secret Key”

Note : This application will not work until you provide your Facebook application’s API keys.

Now to get started with actual coding:

Append Following code in FacebookAPIAppDelegate.h
[objc highlight=”2,3,10,16″]
#import&lt;UIKit/UIKit.h&gt;
#import &quot;FBConnect/FBConnect.h&quot;
#import &quot;FBConnect/FBSession.h&quot;

@class FacebookAPIViewController;

@interface FacebookAPIAppDelegate : NSObject {
UIWindow *window;
FacebookAPIViewController *viewController;
FBSession *_session;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet
FacebookAPIViewController *viewController;
@property (nonatomic,retain) FBSession *_session;
@end
[/objc]
Append Following code in FacebookAPIAppDelegate.m
[objc highlight=”8,20″]
#import &quot;FacebookAPIAppDelegate.h&quot;
#import &quot;FacebookAPIViewController.h&quot;

@implementation FacebookAPIAppDelegate

@synthesize window;
@synthesize viewController;
@synthesize _session;

– (void)applicationDidFinishLaunching:(UIApplication *)application {

// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}

– (void)dealloc {
[_session release];
[viewController release];
[window release];
[super dealloc];
}

@end
[/objc]
Here in FacebookAPIAppDelegate we have just declared _session variable of type FBSession to keep track of the session and to check if session for current user exists or not.

Append Following code in FacebookAPIViewController.h
[objc highlight=”7,8,9,10,11,14,15,16,17,18,20,21,22″]
#import &lt;UIKit/UIKit.h&gt;

#import &quot;FBConnect/FBConnect.h&quot;
#import &quot;FBConnect/FBSession.h&quot;

@interface FacebookAPIViewController : UIViewController {
FBLoginButton *loginButton;
UIAlertView *facebookAlert;
FBSession *usersession;
NSString *username;
BOOL post;
}

@property(nonatomic,retain) FBLoginButton *loginButton;
@property(nonatomic,retain) UIAlertView *facebookAlert;
@property(nonatomic,retain) FBSession *usersession;
@property(nonatomic,retain) NSString *username;
@property(nonatomic,assign) BOOL post;

– (BOOL)textFieldShouldReturn:(UITextField *)textField;
-(void)getFacebookName;
-(void)postToWall;

@end
[/objc]

Append Following code in FacebookAPIViewController.m
[objc highlight=”4,5,8,9,10,11,12,15,16,17,18,19,20,21,22,23,24,25,26,32,33,34,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94″]
#import &quot;FacebookAPIViewController.h&quot;
#import &quot;FacebookAPIAppDelegate.h&quot;

#define _APP_KEY @&quot;Your API Key Goes here&quot;
#define _SECRET_KEY @&quot;Your Secrete Key Goes here&quot;

@implementation FacebookAPIViewController
@synthesize loginButton;
@synthesize facebookAlert;
@synthesize usersession;
@synthesize username;
@synthesize post;

– (void)viewDidLoad {
FacebookAPIAppDelegate *appDelegate =
(FacebookAPIAppDelegate *) [[UIApplication
sharedApplication]delegate];
if (appDelegate._session == nil){
appDelegate._session = [FBSession
sessionForApplication:_APP_KEY
secret:_SECRET_KEY delegate:self];
}
if(self.loginButton == NULL)
self.loginButton = [[[FBLoginButton alloc] init] autorelease];
loginButton.frame = CGRectMake(0, 0, 100, 50);
[self.view addSubview:loginButton];

[super viewDidLoad];
}

– (void)dealloc {
[username release];
[usersession release];
[loginButton release];
[super dealloc];
}

– (void)session:(FBSession*)session didLogin:(FBUID)uid {
self.usersession =session;
NSLog(@&quot;User with id %lld logged in.&quot;, uid);
[self getFacebookName];
}

– (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:
@&quot;select uid,name from user where uid == %lld&quot;,
self.usersession.uid];
NSDictionary* params =
[NSDictionary dictionaryWithObject:fql
forKey:@&quot;query&quot;];
[[FBRequest requestWithDelegate:self]
call:@&quot;facebook.fql.query&quot; params:params];
self.post=YES;
}

– (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:@&quot;facebook.fql.query&quot;]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:@&quot;name&quot;];
self.username = name;

if (self.post) {
[self postToWall];
self.post = NO;
}
}
}

– (void)postToWall {

FBStreamDialog *dialog = [[[FBStreamDialog alloc] init]
autorelease];
dialog.userMessagePrompt = @&quot;Enter your message:&quot;;
dialog.attachment = [NSString
stringWithFormat:@&quot;{\&quot;name\&quot;:\&quot;Facebook Connect for
iPhone\&quot;,\&quot;href\&quot;:\&quot;http://developers.facebook.com/
connect.phptab=iphone\&quot;,\&quot;caption\&quot;:\&quot;Caption\&quot;,
\&quot;description\&quot;:\&quot;Description\&quot;,\&quot;media\&quot;:[{\&quot;type\&quot;:
\&quot;image\&quot;,\&quot;src\&quot;:\&quot;http://img40.yfrog.com/img40/
5914/iphoneconnectbtn.jpg\&quot;,\&quot;href\&quot;:
\&quot;http://developers.facebook.com/connect.php?
tab=iphone/\&quot;}],\&quot;properties\&quot;:{\&quot;another link\&quot;:
{\&quot;text\&quot;:\&quot;Facebook home page\&quot;,\&quot;href\&quot;:
\&quot;http://www.facebook.com\&quot;}}}&quot;];

[dialog show];

}

– (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}

@end
[/objc]
Define API key and Secret key with the keys you received while registering your app on facebook.
[objc]
#define _APP_KEY @&quot;43e37a535cc09c2013bd76fde78dfcc7&quot;
#define _SECRET_KEY @&quot;cc14801521a0c4d1dc31b7cacb891072&quot;
[/objc]
Validate session variable in ViewDidLoad. If it doesn’t exist then create the same for using API key and Secret key. For that, one needs to conform the protocol FBSessionDelegate in respective header file. Also create a login button using FBLoginButton.

While implementing protocol FBSessionDelegate one needs to implement following mandatory method
[objc]
(void)session:(FBSession*)session didLogin:(FBUID)uid
[/objc]
This methos is automatically called when user is logged in using FBConnect SDK.
In this method we get session for that user and it’s uid which unique identifier for that user.

Once FBSession session is avaiable, we can accesss all the APIs provided by Facebook.
For now, we will see how to post user name and status on the facebook wall.

To get Facebook username a request is send in which select query is written to get username using uid.
[objc]
NSString* fql = [NSString stringWithFormat:
@&quot;select uid,name from user where uid == %lld&quot;, self.usersession.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@&quot;query&quot;];
[[FBRequest requestWithDelegate:self] call:@&quot;facebook.fql.query&quot; params:params];
[/objc]
Override following FBRequestDelegate method to check the reponse of above query.
[objc]
(void)request:(FBRequest*)request didLoad:(id)result
[/objc]
The argument result is an array of NSDictionary Objects which contains info for that user as key-value pairs. Retrieve it as follows:
[objc]
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:@&quot;name&quot;];
[/objc]
Use FBStreamDialog class post message on the facbook wall. A dialog pops up with a message box to post on Wall.
[objc]
FBStreamDialog *dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = @&quot;Enter your message:&quot;;
dialog.attachment = [NSString stringWithFormat:@&quot;{\&quot;name\&quot;:\&quot;Facebook Connect for iPhone\&quot;,\&quot;href\&quot;:\&quot;http://developers.facebook.com/connect.php?tab=iphone\&quot;,\&quot;caption\&quot;:\&quot;Caption\&quot;,\&quot;description\&quot;:\&quot;Description\&quot;,\&quot;media\&quot;:[{\&quot;type\&quot;:\&quot;image\&quot;,\&quot;src\&quot;:\&quot;http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\&quot;,\&quot;href\&quot;:\&quot;http://developers.facebook.com/connect.php?tab=iphone/\&quot;}],\&quot;properties\&quot;:{\&quot;another link\&quot;:{\&quot;text\&quot;:\&quot;Facebook home page\&quot;,\&quot;href\&quot;:\&quot;http://www.facebook.com\&quot;}}}&quot;];
[dialog show];
[/objc]
Now Save project (Command +S). Build and Run Project.
Simulator will look like as follows

iPhone FBConnect: Facebook Connect Tutorial

Click on Fconnect Button and Facebook Login Dialog will appear.

iPhone FBConnect: Facebook Connect Tutorial

Login with your user name and Password . Wait for untill post to Wall Dialog pops up

iPhone FBConnect: Facebook Connect Tutorial

The Msg on Facebook will something look like this

iPhone FBConnect: Facebook Connect Tutorial

You can download the source code from here

  • Anele Ivanova

    Hi,

    Recently I came across some great articles on your site.
    The other day, I was discussing (http://mobisoftinfotech.com/iphone-fbconnect-facebook-connect-tutorial/)with my colleagues and they suggested I submit an article of my own. Your site is just perfect for what I have written!
    Would it be ok to submit the article? It is free of charge, of course!

    Let me know what you think
    Contact me at anelieivanova@gmail.com

    Regards
    Anele Ivanova

  • Ashish

    Hi, i am using fbconnect from long in my iOS app.but suddenly it has stopped working, in sense iafter login it doest not post the comment on wall instead it open my feed page. can u please suggest me wats wrong going on.it will be a great help.
    Thanks.

  • http://sourabhshroff.com Sourabh

    Hi Ashish,
    It’s been long time Facebook stop support for fbconnect.
    Now Facebook support SSO (Single Sign On) they have update their SDK for the same.
    Please refer to my post on Facebook SSO (http://mobisoftinfotech.com/facebook-ios-sdk-tutorial-iphone-app-facebook-integration-with-sso-single-sign-on/)

    let me know if you are facing any issue for Facebook’s new SDK.

    Regards,
    Sourabh P. Shroff

  • http://www.wrafik.com/shockied-com-tech-news-portal/ entertainment

    Good information. Lucky me I came across your site by accident (stumbleupon).
    I have saved it for later!