FacebookAgent: Easy way to integrate facebook connect in iPhone Apps and write minimum code to publish feed, change status etc!

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 4.50 out of 5)
Loading ... Loading ...

Today most of the applications we build have a common feature: Socialize! One common way to achieve this my integrating Facebook within the app.

In my earlier post I have shared a helper class for paginating data. Today I will share how I integrate facebook connect in iPhone apps. I humble admit I am a lazy, if not busy, developer who doesn’t like to write same code again again.

For iPhone applications FacebookConnect is the only way to integrate facebook social features. Facebook team has developed a sdk for iPhone. A sample code showing the use and integration of Facebook Connect in your application. This is quite simple and also tons of tutorials, forums, e-books and videos are out here on the web.

Well, I’m not gonna add few more grams on that! Rather I am going to share how I integrates facebook connects into my apps.

Firstly, let us see what are the steps to add facebook connect. You can also check out this tutorial on facebook wiki or watch the video Implement Facebook Connect on the iPhone in 5 minutes.

Basically the steps for publishing a feed are:

1. Download the sdk.

2. Add the connect source file in your project.
project
3. Update the settings to make FBConnect.h in you header path.

4. In the controller class, have session member variable, many delegate methods.

5. Have a login button to show the login prompt.

6. Once logged in, prepare an attachment json string and show the feed dialog.

These steps are quite simple but if you are a busy programmer and need to work on many projects these steps may be little bothering since you have to rewrite all the codes for loggin in, showing dialogs, handle login events etc.

So, I just encapsulated these repetitive work into a class named FacebookAgent and defined a simple protocol to work on.

Lets see how we can use it.

Objective: Create a simple view based application and publish a feed using FacebookAgent.

1. Download this folder FacebookAgent.zip.

It also includes facebook connect sdk. So you don’t need to add this sdk elsewhere or even update any project settings for this purpose.

2. Create a new project, name it FacebookAgentTest. Righ click on the project in the XCode and select Add existing files. Add the FacebookAgent Folder to your classes. Check copy the source files.

Add FacebookAgent folder to your project

3.  In the FacebookAgentTestViewController.h, import FacebookAgent.h and implement protocol FacebookAgentDelegate.

@interface FacebookAgentTestViewController : UIViewController {
...

4. Declare a member variable of type FacebookAgent.

FacebookAgent* fbAgent;

5. Open FacebookAgentTest.m and initialize fbAgent in viewDidLoad method.

fbAgent = [[FacebookAgent alloc] initWithApiKey:@"PLACE YOUR FACEBOOK APPLICATION API KEY"
										  ApiSecret:@"PLACE YOUR FACEBOOK APPLICATION API SECRET"
										   ApiProxy:nil];
	fbAgent.delegate = self;

6. Declare an IBAction method in the FacebookAgentTest.h file.

-(IBAction)updateStatus:(id)sender;

7. Define the above method in FacebookAgentTest.m file.

-(IBAction)updateStatus:(id)sender{
}

8. Open FacebookAgentTestViewController.xib and add a button in the view and connect the above method on its touchesUpInside signal.

9. Now just add the following lines in the updateStatus method to publish a feed!

-(IBAction)updateStatus:(id)sender{
[fbAgent publishFeedWithName:@"Hellow world"
					 captionText:@"how are you?"
						imageurl:@"http://amanpages.com/wordpress/wp-content/uploads/2009/12/logo2.png"
						 linkurl:@"http://amanpages.com/"
			   userMessagePrompt:@"What do you think:"];
}

This code will first check if the user is logged in. If logged in it will show the feed dialog.
If the user is not logged in already, first the login dialog will be shown, after logging in, the feed dialog will be shown automatically!

But one minute, there is one require method in the FacebookAgentDelegate protocol. So, you need to define this:

- (void) facebookAgent:(FacebookAgent*)agent loginStatus:(BOOL) loggedIn{
}

Above method is called when the user logs in or logs out of the facebook. If you use any login button which is very likely, you may change the button title here.

10. Try updating your status. For this use this line:

[fbAgent setStatus:@"status from iPhone 1"];

This will first check if the user is logged in. if not logged in, then it will show the login prompt first.
After log in it will check if extended permission is enabled for this app. if not it will show the permission dialog.
Having given the permission, it will change the user status.

BUT.

11. You need to two more FacebookAgentDelegate method if you want to change status:

- (void) facebookAgent:(FacebookAgent*)agent requestFaild:(NSString*) message{
}
- (void) facebookAgent:(FacebookAgent*)agent statusChanged:(BOOL) success{
}

12. Thats all :) Run the app!

You can look into the FacebookAgent.h for more detail. It is well documented. If you still have some question shoot here or drop me mail.
Feel free to use this classes without any restriction but I will appreciate if you let me know in which app you are using it :)

What can be done now using FacebookAgent:
1. Fetch user name:
For this after initialization, set shouldFetchUsernameAfterLogin = YES.

fbAgent.shouldFetchUsernameAfterLogin = YES

and also define the corresponding delegate method:

- (void) facebookAgent:(FacebookAgent*)agent didLoadName:(NSString*) name{
    //use the name
}

2. Make your own attachment and publish a feed.

// this method has some over loaded versions too
- (void) publishFeed:(NSString*)attachement;

3. Publish feed by passing, name, caption, image and link url.

// this method has some over loaded versions too
/**
 * Let the agent make attachement for you. You just pass the information
 *
 */
- (void) publishFeedWithName:(NSString*)name
			 captionText:(NSString*)caption
					   imageurl:(NSString*)url
						linkurl:(NSString*)href
			  userMessagePrompt:(NSString*)prompt;

4. upload a photo

- (void) uploadPhoto:(NSString*)imageurl;

6. ask for extended permission

- (void) askPermission;

7. login and logout

- (void) login;
- (void) logout;

The delegates also offers some handy callback options like:

/**
 * Must define this method if setStatus is called
 *
 * This method is called when user status is changed either successfully or not
 */
- (void) facebookAgent:(FacebookAgent*)agent statusChanged:(BOOL) success;

/**
 * Must define this method if shouldFetchUsernameAfterLogin is set YES
 *
 * This method is called after the agent fetched facebook profile name
 */
- (void) facebookAgent:(FacebookAgent*)agent didLoadName:(NSString*) name;

/**
 * Must define this method if uploadPhoto is called
 *
 * This method is called after photo is uploaded
 */
- (void) facebookAgent:(FacebookAgent*)agent photoUploaded:(NSString*) pid;

/**
 * Must impement this method if any of the above method is defined
 *
 * This method is called if the agent fails to perform any of the above three actions
 */
- (void) facebookAgent:(FacebookAgent*)agent requestFaild:(NSString*) message;

@required

/**
 * This method is called if after login or logout
 */
- (void) facebookAgent:(FacebookAgent*)agent loginStatus:(BOOL) loggedIn;

Here is the demo project. DONT FORGET TO ADD YOUR key and secret!!
FacebookAgentTest




Add to Google Reader or Homepage


  • This looks excellent. Thanks for sharing the code.

    I have a question: what are the terms for using this code in our own projects?

    Thanks!
  • No terms! you can use it as your own code for any project... but I will appreciate if you fix any bug and share the link :)
  • Thanks! I will definitely share any fixes if there are any :)
  • Cam
    Nevermind, I just replaced the album name string with nil, and that worked!
  • thanks for using it :)
  • Jorge
    Aman, Thanks for this. I've been playing with the project all afternoon and would love to use this in my next app and give you proper credit. Shoot me an email to jorge AT ripprapp DOT com and let me know if there's anything in particular you'd like to see, I can also give you some info about the app
  • Cam
    Great, this is really helpful so far! I like how you fit everything into just one header and one implementation file.

    Is there any way to automatically create a photo album if it doesn't already exist? Right now, I'm getting a "Error(120) Invalid album id" response when trying to upload a photo. I'd like it to try to create a photo album called "My Drawings" and I'm not sure how to integrate this with fbAgent
  • dev
    Hello. I tried the example, the publish feed works fine and when using the image url I see the image on the facebook wall as expected. great!

    But if I run this code :

    NSData * myData = UIImageJPEGRepresentation(imageView.image,1);
    [fbAgent uploadPhotoAsData:myData withCaption:@"a caption" toAlbum:@"an album"];


    The application crashes after I have logged in to facebook with this in the console :

    2010-01-21 18:14:13.997 facebookExperiments[4520:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
    2010-01-21 18:14:13.999 facebookExperiments[4520:207] Stack: (
    29402203, etc etc



    I have an image in my imageView, the code is run by a button press in a view controller.

    I also tried it with UIImagePNGRepresentation in case the data is required in that format, with the same result.

    Am I doing something wrong?
  • hello dev,
    sorry, it was a bug, my mistake.

    Please go to near line 202 in FacebookAgent.m. You will find a method like this:
    -(void)uploadImage{
    NSDictionary *params;
    ---
    change NSDictionary to NSMutableDictionary.

    -----

    This is found and fixed by danbaumbach.

    He shared here:
    http://amanpages.com/iphone-app-development-cor...


    Thanks.
blog comments powered by Disqus