How to develop facebook application for iphone

iphoneSomeday ago Facebook updated their old SDK for iphone and release a new SDK named IOS Library. This open source iOS library allows you to integrate Facebook into your iOS application include iPhone, iPad and iPod touch. Now its really very easy to implement facebook features in your iOS applications.

Why we should implement Facebook in iOS application:

  1. According to techcrunch Facebook Mobile Hits 100 Million Users, Growing Faster Than On Desktops. So you  can think there are lots of users are now using facebook from iOS base devices.
  2. According to AppleInsider iPhone sales predicted to top 80 million by 2012
  3. So people are using iPhone/iPod/iPad more now a days. And the number is growing both for facebook and iOS.
  4. Why not consider to include facebook users  in your iOS application so that your application looks more social.

A typical scenario of facebook features in iOS application:

Suppose you develop a game for iOS. You’ve a online leaderboard system for that game. Now people can compare themselves in the game based on leaderboard. But there might be many fake profile in the leaderboard, because you’re not aware of who’s playing the game. Though facebook has many fake account, but normally a user has real friends in facebook. So you can bring facebook user’s real friends in your application, so that the user feel more proud when he will be in a higher rank among his facebook friends.

So normally you could implement these facebook features in your iOS application:

For a iOS game application:

  1. Inspire user to connect facebook and brings the data of his friends who already played the game
  2. When user make higher rank among his friends then show popup to user to publish this news in his wall and friends wall
  3. If user achieve some good score, show a popup to user to publish the happy news in facebook.

So using facebook’s viral features you can easily market your application to a broad audience.

\

So you’re inspired to integrate facebook features in your iOS application. I assume you’re using Mac and already installed XCode and you know the basics of how to develop iOS application using XCode and Objective C. Now follow the steps:

  1. Visit http://github.com/facebook/facebook-ios-sdk/ and download SDK in your laptop
    Mahmuds-MacBook-Pro:~ mahmud$ git clone 'http://github.com/erica/iphone-3.0-cookbook-.git'
    
  2. In the SDK, now open facebook-ios-sdk/sample/DemoApp/DemoApp.xcodeproj
  3. Now see the code in Classes/DemoAppViewController.m and create a facebook app and get the appId and place that id in by replacing nil at kAppId variable.
    static NSString* kAppId = @"1234444444"; //here 123..... would be your actual app id

    Code Modify

  4. Now build and run the application in your device and test yourself.
  5. The demo application source code is nicely written. You can easily reuse them for your purpose.
  6. In the demo you’ll see the following code samples,
    1. how to authenticate user in facebook
      - (void) login {
        [_facebook authorize:kAppId permissions:_permissions delegate:self];
      }
      
    2. how to call graph api and retrieve information
      - (IBAction) getUserInfo: (id)sender {
        [_facebook requestWithGraphPath:@"me" andDelegate:self];
      }
      
    3. how to call rest api
      /**
       * Example of REST API CAll
       *
       * This lets you make a REST API Call to get a user's public information with FQL.
       */
      - (IBAction) getPublicInfo: (id)sender {
        NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        @"SELECT uid,name FROM user WHERE uid=4", @"query",
                                        nil];
        [_facebook requestWithMethodName: @"fql.query"
                               andParams: params
                           andHttpMethod: @"POST"
                             andDelegate: self];
      }
      
    4. how to show popup to publish wall post
      - (IBAction) publishStream: (id)sender {
      
        SBJSON *jsonWriter = [[SBJSON new] autorelease];
      
        NSDictionary* actionLinks = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:
                                     @"Always Running",@"text",@"http://itsti.me/",@"href", nil], nil];
      
        NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];
        NSDictionary* attachment = [NSDictionary dictionaryWithObjectsAndKeys:
                                     @"a long run", @"name",
                                     @"The Facebook Running app", @"caption",
                                     @"it is fun", @"description",
                                     @"http://itsti.me/", @"href", nil];
        NSString *attachmentStr = [jsonWriter stringWithObject:attachment];
        NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       kAppId, @"api_key",
                                       @"Share on Facebook",  @"user_message_prompt",
                                       actionLinksStr, @"action_links",
                                       attachmentStr, @"attachment",
                                       nil];
      
        [_facebook dialog: @"stream.publish"
                andParams: params
              andDelegate:self];
      
      }
      
      
    5. how to upload photos in facebook
      -(IBAction) uploadPhoto: (id)sender {
        NSString *path = @"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg";
        NSURL    *url  = [NSURL URLWithString:path];
        NSData   *data = [NSData dataWithContentsOfURL:url];
        UIImage  *img  = [[UIImage alloc] initWithData:data];
      
        NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        img, @"picture",
                                        nil];
        [_facebook requestWithMethodName: @"photos.upload"
                               andParams: params
                           andHttpMethod: @"POST"
                             andDelegate: self];
        [img release];
      }
      

    The SDK’s code are very easy to understand and well documented. Also don’t forget to follow the official tutorial of facebook

    So you could easily develop iOS base facebook application or you can implement necessary facebook features in your iOS application. So don’t be late, go buddy go :D

    Hope this article will help you to make social iOS application.

About mahmud ahsan

Programming is my passion from high school. I always looking for innovating new ideas and making them real application. I love mobile application and game development as well as web development. Having 4+ years web development experience and 6+ years mobile application development experience on different platform and business on it. My Mobile Apps Portfolio: iThinkdiff.net Mobile Apps

, , , , , ,

56 Responses to How to develop facebook application for iphone

  1. ccarrasco August 22, 2010 at 3:40 am #

    you knowledge is awesome thanks Mahmud !! :)

    • mahmud ahsan August 22, 2010 at 6:08 pm #

      @Ccarrasco, thank you. Actually Objective C is a nice language to work with. And I’m working in iphone as a hobby :)

  2. sagi August 23, 2010 at 5:55 pm #

    Hi, great article, I also took a look at the new sdk… actually, I’m having a problem with the post-stream action, can you pls explain how to extend it so my post will have an image next to it, I have a valid image url, and I tried adding it to the ‘attachments’ dictionary as : @”my_pic_url”, @”picture”

    but still I get the default image placeholder next to my post….

    • mahmud ahsan August 24, 2010 at 12:29 am #

      @Sagi,
      I found the problem as you told and fixed it. Just follow the code:

      - (IBAction) publishStream: (id)sender {
        
        SBJSON *jsonWriter = [[SBJSON new] autorelease];
        
        NSDictionary* actionLinks = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys: 
                                     @"Always Running",@"text",@"http://thinkdiff.net",@"href", nil], nil];
        
        NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];
        NSDictionary* imageShare = [NSDictionary dictionaryWithObjectsAndKeys: 
                                      @"image", @"type",
                                      @"http://thinkdiff.net/mahmud_small.jpg", @"src",
                                      @"http://thinkdiff.net", @"href",
                                      nil];
          
        NSDictionary* attachment = [NSDictionary dictionaryWithObjectsAndKeys:
                                     @"a long run", @"name",
                                     @"The Facebook Running app", @"caption",
                                     @"it is fun", @"description",
                                     @"http://itsti.me/", @"href", 
                                     [NSArray arrayWithObjects:imageShare, nil ], @"media",
                                    nil];
        NSString *attachmentStr = [jsonWriter stringWithObject:attachment];
          NSLog(attachmentStr);
        NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       kAppId, @"api_key",
                                       @"Share on Facebook",  @"user_message_prompt",
                                       actionLinksStr, @"action_links",
                                       attachmentStr, @"attachment",
                                       nil];
        
        
        [_facebook dialog: @"stream.publish"
                andParams: params
              andDelegate:self];
      }
      

      The image part should be another NSDictionary object.

      NSDictionary* imageShare = [NSDictionary dictionaryWithObjectsAndKeys: 
                                      @"image", @"type",
                                      @"http://thinkdiff.net/mahmud_small.jpg", @"src",
                                      @"http://thinkdiff.net", @"href",
                                      nil];
      

      And in the attachment NSDictionary object must include imageShare object as array

      [NSArray arrayWithObjects:imageShare, nil ]
      

      This is because if you not include this as an array, Json parser avoid [] brackets as a result the publish functionality will not work. Remember the string needs to be a valid JSON string otherwise facebook api will not publish.

      • sagi August 25, 2010 at 2:11 am #

        thanks, that did the trick.. actually I already tried that before I posted my comment.. but I made a small mistake: I first converted the ‘media’ object into JSON array […] string, and then included it in the ‘attachments’ dictionary. I didn’t realize I need to put it as a native NSArray with a NSDictionary inside it. thanks!

      • Kris January 8, 2011 at 2:54 pm #

        Thanks for the tip on adding the image to the post. Was trying to track it down in the API docs but it wasn’t spelled out like you have it.

  3. Markus August 24, 2010 at 3:59 pm #

    Great tutorial!
    My problem is just that the login view doesn’t get posted on top of my actuall ui. I reallyzed it gets posted just on the main window. As I put my TableView controller on it, the login dialog doesn’t get displayed… (just in the background) how can I solve that?
    Thanks

  4. Phil August 26, 2010 at 1:43 pm #

    This line is in the FBLoginButton.m file in the DemoApp project but I can’t find it anywhere in the project. Can you explain? Thx.

    #import

  5. Phil August 26, 2010 at 1:46 pm #

    OK I give up… it’s the import on line 20 of FBLoginButton.m

  6. Alex September 19, 2010 at 6:55 pm #

    Hey, I tried the new SDK, but there’s something really bothering me. It seems that every time I load the App, and even push a window after it’s been popped, the session ends and I have to log in again.
    How can I resume a session like with the old iPhone SDK?
    The structure of the app is like this:
    didSelectRowAtIndexPath loads a window with an article. In that window, there’s a button for FB sharing. In order to use it I have to login every time. The Facebook variable is released and initialized like this:

    - (void)viewDidLoad {
    	[super viewDidLoad];
    
    	_facebook = [[[[Facebook alloc] init] autorelease] retain];
    }
    
    - (void)dealloc {
    	[_facebook release];
    	[super dealloc];
    }
    

    Am I doing something wrong?

    • JWeldin September 20, 2010 at 11:23 am #

      Check out the sample app theRunAround included in the SDK. Specifically look at how mainViewController uses the Session object.

    • nathan September 21, 2010 at 12:27 am #

      definitely make sure rootviewcontroller users the object properly. you can also look at adding the offline param to your permissions request to avoid prompting users to constantly login via your app

  7. Alex September 21, 2010 at 12:31 am #

    Thanks for the help! I took a closer look at the SDK documentation and found out that the Facebook iOS SDK doesn’t handle the session storage. It was foolish of me to overlook that in the first place.
    I fixed the error now and everything works like a charm. I sent the app for review so keep your fingers crossed for me :D
    By the way, the app its called TheGossiper and as a thanks for your help I’ll fix you up with some promo codes. Just give me a reply if you’re interested.

    • mahmud ahsan September 21, 2010 at 2:57 am #

      Nice to know that you found the solution and informed us. Waiting to see your application and all the best wishes :)

  8. BigB October 4, 2010 at 12:58 pm #

    How would I post a dynamic nsstring say like a highscore? I can easily change the static text but I can’t seem to find a way to integrate an nsstring in place of say the “it is fun” in the description part of the post.

  9. Keith November 2, 2010 at 4:06 am #

    Wow! Great sdk! With the included samples, it took about an hour to integrate FB into my app! Good job everyone!

  10. Romulo November 13, 2010 at 6:31 pm #

    Have you tried using the latest version in the github? I am having problem with that exact method, publishStream() .. I cannot publish with Dialog error of “An error occurred with [APP_NAME]. Please try again later.”

    Did you encounter such problem when running the demo app with publishing?

  11. kuldeepsidhu November 19, 2010 at 4:51 pm #

    Everything ok…but i want to change it…that user can write the post in text field and then clicking on publish button (in iphone view.) post this to the user wall..is this possible??

    i dont want to show the pop up when we click on publish stream..is this possible??

  12. Alex November 21, 2010 at 11:56 am #

    I tried to run the new sdk, I can login, upload photo,
    but I couldn’t publish stream, it gives me Error message ,I followed the steps mentioned in sdk example.

    any help plz?

  13. Andrew December 7, 2010 at 5:44 am #

    I’m having the same error problem
    I implemented it and logged in, but everytime I try to post a status update the blue box comes up with an error message: An error occured. Please try again later.

    Can anyone help

    Thanks in advance
    Andrew

  14. Idris December 15, 2010 at 4:24 pm #

    Great Tutorial !!!.
    But I am having problem of retaining the session,
    I need my app, to stay logged in, even after redirecting to “touch.facebook.com” but the login screen is displayed, what should be passed exactly to redirect URL, (entire format) ?

    • mahmud ahsan December 16, 2010 at 10:20 pm #

      In the facebook connect demo by facebook, they showed it how to retain session and use. Please check it out.

  15. cybernet December 21, 2010 at 10:59 pm #

    Ultimate Facebook App

    Advance facebook client for iPhone/iPod-Touch
    Quickly Upload Videos and Photos to Facebook directly from iPhone. Share photos and videos with friends and family on facebook.

    Includes 4 FREE Bonus Apps
    1. Phrases/Quick Status – Update your Facebook status with one-click, app contains pre-loaded popular facebook status’s – you can even create your own frequently used status updates.2. Birthday Reminder – Send Virtual Gifts to your friends.3. Watch Facebook videos. 4. View and Create Facebook Events. Geotag your photos on-the-go to automatically capture location data as you shoot. Capture the perfect moments on your iPhone’s camera and instantly share with your friends on Facebook. Make black & white portraits out of color photos. * DoodlePro – a fun app for drawing with fingers and Face Detection. * Birthday reminder – tracks upcoming birthdays of your friends on Facebook. You can even send Virtual Gifts to your friends. * Finding friends Nearby * Check Friends who are online. *

    *Download from iTunes:http://itunes.apple.com/us/app/facebook-video-photo-uploader/id349427597?mt=8

  16. cygnis media December 30, 2010 at 5:00 pm #

    Nice, and thanks for sharing this info with us.
    Good Luck!

  17. DrAma January 22, 2011 at 10:23 pm #

    I’m getting crazy. I can’t understand why when I use the demo app inside the sdk and ask to publish a stream(even if I modify permissions), it just publish what i post and not all the data in the sample application (the running facebook test). Could it be related to privacy settings in facebook?

  18. Daniel January 26, 2011 at 6:29 pm #

    Hi…. i just try the code “stream.publis” and it works well repopulate my post, but the problem is if i use the “_facebook dialog: @”stream.publish”…. my app will publish only to my wall and not to my news feed…. can someone help me?… thanks in advance

  19. Dave January 30, 2011 at 5:03 am #

    Instead of using a URL for the image, I would like to use a UIImage object to post the image. Is that possible, if so what changes would be needed to use a UIImage.

    I think here’s the code that would need to be changed.

    NSDictionary* imageShare = [NSDictionary dictionaryWithObjectsAndKeys:
    @”image”, @”type”,
    @”http://thinkdiff.net/mahmud_small.jpg”, @”src”,
    @”http://thinkdiff.net”, @”href”,
    nil];

    • mahmud ahsan January 30, 2011 at 8:13 pm #

      @Dave, I’m not sure if its possible or not. But as far as I know this is not possible.

  20. Sanjeev February 16, 2011 at 9:39 pm #

    how to get youtube link from news feed of a user after login with facebook credentials in App.

  21. YUVARAJ.M March 4, 2011 at 11:16 am #

    Hi all. I want to known to upload images on facebook via fbconnect from iphone. Am new to iphone, am struggle with this task can anyone help me. Below is my code, am using FBConncet.
    -(void) posttowall
    {
    NSMutableDictionary *args = [[[NSMutableDictionary alloc] init] autorelease];
    [args setObject:fbimages forKey:@”image”]; // ‘fbimages’ is an NSArray of ‘UIImage’ objects,
    FBRequest *uploadPhotoRequest = [[[FBRequest alloc] init] autorelease];
    uploadPhotoRequest = [FBRequest requestWithDelegate:self];
    [uploadPhotoRequest call:@”facebook.photos.upload” params:args];
    //[[FBRequest requestWithDelegate:self] call:@”facebook.photos.upload” params:args];
    NSLog(@”uploading image is successful”)
    }

  22. Sinan KUTAS March 13, 2011 at 3:12 am #

    i want send to image upload request. I received the error when come back response. it description is “errorDomain101″.

    What does it means ???

  23. awes May 26, 2011 at 11:47 am #

    i want to post to my friend some message how to do it…

    i am using git hub wala code.

  24. Rohit June 14, 2011 at 6:35 pm #

    thanks for this , i want to publish facebook checkins and want to post comment on locations , will you please help me. thanks in advance.

  25. .sA.r July 18, 2011 at 8:45 pm #

    Hey ! Thanks for sharing this. Great job.

    But i’m still sad that the API doesn’t allow you to share photos taken with your application.

    Hope they gonna update it asap.

  26. iPhone Apps Review August 2, 2011 at 9:57 am #

    Once again you wrote amazing post for us.

  27. Gal August 5, 2011 at 7:51 pm #

    Thank you for this post.
    1. Why the photo only appears once on the wall? I’d like it to appear each time I post?
    2. Why the text doesn’t appear with the photo?

    Thanks!

  28. Goldman August 7, 2011 at 12:58 am #

    Hi,
    On Publishstream methods, how to use textView.text for description to publish to the wall instead the user needs to fill the text box.
    Please help!

  29. Điện toán đám mây August 13, 2011 at 5:10 pm #

    @ iPhone Apps Review: Thanks.
    admin: our small team intends to create a simple quiz app for student survey on Facebook. your post is really useful for code rules. ;)

  30. sadu August 16, 2011 at 11:57 am #

    wat is this? same as in the sample provided by facebook developers

  31. Jonathan October 19, 2011 at 8:20 am #

    how do I get the session uid? I tried to use get the name and email in the request, but I get Mark Zuckerberg for uid=4. Thanks

    • Jonathan October 19, 2011 at 8:24 am #

      Found out that you don’t need a session to access user info. should be uid=me() in the SQL statement

  32. George Varghese December 12, 2011 at 3:36 pm #

    Hello,

    I am using this sdk but I didn’t got fbDidLogin callback,
    I got the error message
    “safari cannot open the page because the address is invalid”

    I didn’t put any redirect uri for this application.

    I am currently using ios SDK 4.2 .

    anybody please help me.

    Regards,
    George

  33. Rohit January 30, 2012 at 11:38 am #

    Can we get all comment on the uploaded photo on facebook. Right now I am using graph api:
    FbGraphResponse *fb_graph_response = [fbGraph doGraphGet:@”me/feed” withGetVars:nil];
    NSLog(@”getMeFeedButtonPressed: %@”, fb_graph_response.htmlResponse);
    But it will not provide the comment on the specific photo. Can you please help me out?

  34. Gadgets April 8, 2012 at 7:17 pm #

    I want to received live call from Facebook on I phone.. Do this possible?

  35. Michele April 23, 2012 at 5:16 am #

    I’m trying to download the sdk and work with your example. I can’t find the sdk downloaded. Where does it wind up and what is it called? Am I looking for it on my mac? I’m sorry but very confused.

  36. Michele April 23, 2012 at 5:39 am #

    Maybe I haven’t downloaded the sdk after all? Where do I download it? Where is the example code to use?

  37. Michele April 23, 2012 at 5:49 am #

    Ok. I think I downloaded it, but there’s an xcode proj called Hackbook, not Demo App. Is that the one for the example?

  38. Bhavik July 6, 2012 at 7:21 pm #

    Hi Mahmud, your facebook example is awesome, its useful for me, thanks for that.
    Have you done any Example for linkedin api ?

  39. siva July 7, 2012 at 11:21 pm #

    Hi

    currently im trying to integrate facebook connect,im new in ios dev.Can you get me simple example to get the details of the firstname,lastname,gender,Dateof birth & email address when the log in to the application,Im trying for the 2 weeks till now i cant able to get the solution.Please provide some simple example to Facebook login & get the details i have mentioned.

  40. santanu July 19, 2012 at 11:44 am #

    How to post audio fille? Please.

  41. cialis May 8, 2013 at 3:03 am #

    Bereits seit mehreren Jahren gilt Viagra als eines der bekanntesten Orgasmusmittel
    fֳ¼r Herren und das aus gutem Grund, denn das Orgasmusprodukt Viagra ist
    absolut wirksam. Original Cialis rezeptfrei

  42. Kizi Games June 27, 2013 at 3:44 am #

    I am truly happy to read this webpage posts which includes plenty
    of helpful facts, thanks for providing these statistics.