Wednesday, August 22, 2012

Post on your facebook wall using graph api

In this post we will study how to post text on your facebook wall and in the second part of the post we will study how to post a text on your friend’s wall. For this demo I will be using the facebook graph api.

The graph API is a powerful set of various apis provided by facebook which helps us in carrying out all the task through a hand held device which we normally do when we are logged in to facebook from a web browser. All the response provided by the graph api is in JSON format.

You can read all about the graph api by visiting this link.

Let’s code

Step 1: Create a view based application using xcode which has one UIButton and UITextField on the view, when the user will touches this button the user will see the facebook pop up where he will enter his credentials and post data on his wall.

Note: Before creating this view I hope that you have created a test application on facebook and are using the application ID of the test application, in case if you don’t know how to create a test application you can visit this link which will help you out.

The test application ID is required because all the posting in the facebook from handheld application is done through apps that are registered with facebook and in case if your application is not registered with facebook then in that case you cannot post your data.

Step 2: Download the graph api latest copy which is present here and add the graph api folder into your project by just dragging and dropping the folder into your project don’t forget to click copy when you are adding the folder by using drag drop method. You can also use the graph api that i have in my demo which is available for download at the bottom of this page. 

I have modified the graph api which i previously downloaded from the given link since it was giving me some crash, also the demo which is available for download is in ARC version.

Step 3: Import the fbgraph into your viewcontroller file, when the user logs in by entering his credential in the graph api pop up their's  a method that will be called by the graph api, this method is no delegate method but its the custom method that you can write yourself.

So now let's have a look at the function which will be called on the UIButton instance

- (IBAction)callFacebookAPI:(id)sender

    if (txtinputfield.text.length !=0
       //create the instance of graph api
        objFBGraph = [[FbGraph alloc]initWithFbClientID:FbClientID];
        //mark some permissions for your access token so that it knows what permissions it has
        [objFBGraph authenticateUserWithCallbackObject:self andSelector:@selector(FBGraphResponse) andExtendedPermissions:@"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins,publish_checkins,email"];
        UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Kindly enter data in the text field" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [objAlert show];

Code Explanation: Above code is self explanatory i am initializing the graph api with the application ID that i created the steps for which are mentioned here.

The method authenticateUserWithCallBackObject:andExtendendPermission will call one method which you can define in the .h file and this method will be called only after the a valid credentials are entered.

Extended permission: When a user authenticates your application by default has the ability to read only the user's basic info and if you want additional permission then you need to add them here.

FBGraphResponse: This is my own method that i have declared in the .h file of the view controller which will be called once the credentials entered are validated.

Step 4: Using the FBGraphResponse method I will be able to know what the response from the facebook server is. Generally the response is the basic information about the user who has entered his credentials in the graph api pop up.

Since the user record is received now it’s time to push some text on the users wall. In our demo the user will enter some text in the text field and that text field data will be posted to the users facebook wall.Posting to the facebook wall is normally referred to as posting to the users feed. 

Note: Maximum of the facebook api work on the access token that is provided to you when you login using the graph api, you can only post data and do stuff with the graph api if your access token is valid and if not then you will receive a server error message from facebook.

- (void)FBGraphResponse

        if (objFBGraph.accessToken
            SBJSON *jsonparser = [[SBJSON alloc]init];
            FbGraphResponse *fb_graph_response = [objFBGraph doGraphGet:@"me" withGetVars:nil];
            NSString *resultString = [NSString stringWithString:fb_graph_response.htmlResponse];

            NSDictionary *dict =  [jsonparser objectWithString:resultString];

            NSLog(@"Dict = %@",dict);
            NSMutableDictionary *variable = [[NSMutableDictionary alloc]initWithCapacity:1];
            [variable setObject:txtinputfield.text forKey:@"message"];
            [objFBGraph doGraphPost:@"me/feed" withPostVars:variable];
            UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"String posted on your wall and you may check the console now" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [objAlert show];
    @catch (NSException *exception) {
        UIAlertView *objALert = [[UIAlertView alloc]initWithTitle:@"Alert" message:[NSString stringWithFormat:@"Something bad happened due to %@",[exception reason]] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [objALert show];
    txtinputfield.text = clearText;

Code Explanation: In facebook "me" means that the developer is interested to know the data of the user who has currently logged in.

By using the doGraphGet method you can get the data of the user and by using the method doGraphPost you can post the data on the users wall.

If you want to post the data on your own wall then in that case you have to give a command like "me/feed" where me stands for the user who is currently logged in and feed will point to the currently logged in users wall feeds.

So in a nutshell what i am doing is i am giving a command to the graph api to post on the users wall (feeds) 

Step 5: Now we are all set so let’s run the application and push data on our facebook wall. Select the app delegate.m file import your view controller and 
add the view controllers view to the iphone window.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    self.objFBPostVC = [[FBPostViewController alloc]init];
    [self.window addSubview:self.objFBPostVC.view];
    [self.window makeKeyAndVisible];
    return YES;

Hit build and go 

i hope that this post has helped you in learning to post data on facebook in my next tutorial i will teach you to get the list of all your friends from facebook and post on their wall.

In case if you are having any queries then kindly mail me up or enter it via comments.

You can download the source code from here.

Join us on facebook iPhone by radix Facebook group.

Until then happy iCoding and have a great day.


  1. Hey Great Work........

    can you please show a demo that how to login using facebook on app and storing the id to database for future reference...

    1. You may use SQLITE but in my opinion NSUserDefault would be a better option.

  2. Hi Radix ,
    can you please explain the code lil more clearly.. i m not able to follow it

  3. Thanks For the good tutorial.I need more on this.I want to post on owners wall without login into FB again and again.I have Userid and pass of user then?
    Please help me..

    1. @Milind J: For this you need to store in the access token and the user ID of the user and then try posting, to do this you can save the credentials in some of the global variable and then probably this should do the trick.

    2. If I have token and user id,then can i post directly?
      Because i can get access token and user id when i logged in 1st time.
      We cannot retrieve password of facebook account when we logged in first time and cant store it :(
      Please elaborate on this.
      Thanks :)

    3. @MJ: See it's a tricky affair here, It's all about valid access token when you post to FB using FBGraph

      - Save the access token in a NSString,

      - In the FBGraphResponse method you will see that their is a line which says

      "[objFBGraph doGraphPost:@"me/feed" withPostVars:variable];"

      This line internally uses the access token if you could drill down to the code and check it out.

      - What you could do is modify the function and supply your stored access token to that function.

      - If the access token is valid then your data will be posted else not.

      - I really don't know about the expiration time of a particular token but if the token is invalid then probably FB will tell you in their response. which would be something like this

      "error": {
      "message": "Error validating access token: User USER_ID has
      not authorized application APP_ID.",
      "type": "OAuthException",
      "code": 190
      "error_subcode": 458

      - If you get an error due to invalid token then you have re-authenticate the application by displaying the FB pop up once again.

      Hope this helps you :)

    4. @IronMan :Thanks :)
      I will try with it.. :)

  4. Hi,
    Can you please tell me if i have some url e.g. and i have to go that url and need to show it user,as its FB link after all. If the user logging in 1st time then it will ask for FB Login page and then will be redirected to the url i mentioned above.Can we do that?
    Or simply can we send the above url to Graph Api and reach to the same page?
    Please Help me..

  5. Thanks for your tutorial. I just wanted to know tha "is it possible to post an image along with caption,link, and description to the facebook wall".

    I used Facebook SDK 3.0 where I done this by setting the image from a URL. But want to include an image from the bundle itself. I know we can use me/photo to add image to the users album.
    But I dont need that.. Is there any possible way to this???

    Thanx ...

  6. how i can check first time of login in Facebook.... can u plz help me.....

  7. @Divya : You can use NSUserDefault to maintain the login count of the user from facebook

  8. one more problem...... only one login is accepting and getting response.... other then that if am giving any other Facebook id insense response is not getting....WHY? what might me solution

  9. one more problem...... only one login is accepting and getting response.... other then that if am giving any other Facebook id insense response is not getting....WHY? what might me solution

  10. Hello,
    I want to do logout functionality in code.For that i think i have to invalidate access token but i don't know how to invalidate access token?

  11. Hi Bhoomi, This code is really old you can download the source from developer.facebook using their SDK which has the source code for logout. Facebook SDK is quite mature now. Will try to find sometime and post may be in future with that SDK