Search code examples
iosiphonefacebookfacebook-likefacebook-page

Like Facebook page on button action


I'm trying to implement page like functionality from application, I've added latest Facebook SDK and implemented all delegates and handlers to check for session and status for the user login to the app. Its working fine up to here (this is already done in the sample code). Anyways, I've found the following code from the Facebook developer site, to like a page, but it doesn't seem to work.

- (void) likeFacebookIndia
{
    NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
    action[@"object"] = @"http://www.facebook.com/FacebookIndia";
    //action[@"object"] = @"FacebookIndia";
    [FBRequestConnection startForPostWithGraphPath:@"me/og.likes"
                                       graphObject:action
                                 completionHandler:^ (FBRequestConnection *connection,
                                                     id result,
                                                     NSError *error)
     {
         // handle the result
         if(error)
         {
             NSLog(@"%@",error.localizedDescription);
         }
         else
         {
             NSLog(@"%@",result);
         }
     }];
}

Once successfully logged in, I used to call above function, and it ends up with the following error in likeFacebookIndia block,

The operation couldn’t be completed. (com.facebook.sdk error 5.)

Here, my questions are,

  1. I am not sure whether this is the correct way for liking a page?

  2. If its correct, then what I am really missing to pass?

  3. Is there any other way?

I already visited pages for FacebookLikeView and FBLikeButton also many question already aksed here, but not a single seems to work with latest Facebook SDK update. I was able to like a page with FacebookLikeView but there's many problems with that,

  1. A UIKeyBoard is showing up after like a page
  2. Takes good time in loading Facebook page if login required and
  3. After second like to the same page, like view goes out somewhere!

Update I tested same thing on Graph API Explorer, and it comes with the following result,

Graph API Explorer

{ "error": { "message": "(#100) Like actions are not yet supported against objects of this type.", "type": "OAuthException", "code": 100 } }

Update 2

I do hacked into FacebookLikeView classes and solved above problems I written, though it should work now? NO it's not working, as it is using FBConnect which is now outdated and also, I've latest Facebook SDK for other stuff which working nicely! It would be good if someone will make new project with latest SDK for FacebookLikeView. [I'm already working!]

This is how I'm doing,

//Calling this function in `viewDidLoad`

- (void) addLikeView
{
    facebookLikeView.delegate = self;
    facebookLikeView.href = [NSURL URLWithString:@"http://www.facebook.com/FacebookIndia"];
    facebookLikeView.layout = @"button_count";
    facebookLikeView.showFaces = NO;
    facebookLikeView.alpha = 0;
    [facebookLikeView load];
}

#pragma mark - Facebook Delegate
-(void)sessionDoneForPageShare:(FBSession *)session state:(FBSessionState)state error:(NSError *)error
{        
    if(error)
    {
        NSLog(@"error : %@",error);
    }
    else
    {
        [facebookLikeView load]; //In logged in or logged out, we've to call this
    }
}

- (void)facebookViewControllerCancelWasPressed:(id)sender
{
    NSLog(@"Login was cancelled by user");
}

- (void)facebookViewControllerDoneWasPressed:(id)sender
{
    NSLog(@"User tapped done button on login view");
}

- (void) checkFBloggedInStatus
{
    if (!FBSession.activeSession.isOpen)
    {
        NSArray *permissions = [NSArray array];
        [FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceOnlyMe allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error){
            [self sessionDoneForPageShare:session state:status error:error];}
         ];
    }
}

#pragma mark FacebookLikeViewDelegate methods
- (void)facebookLikeViewRequiresLogin:(FacebookLikeView *)aFacebookLikeView {
    [self checkFBloggedInStatus];
}

- (void)facebookLikeViewDidRender:(FacebookLikeView *)aFacebookLikeView {
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDelay:0.5];
    facebookLikeView.alpha = 1;
    [UIView commitAnimations];
}

- (void)facebookLikeViewDidLike:(FacebookLikeView *)aFacebookLikeView {
    NSLog(@"liked");
}

- (void)facebookLikeViewDidUnlike:(FacebookLikeView *)aFacebookLikeView {
    NSLog(@"unliked");
}

- (void)facebookLikeView:(FacebookLikeView *)aFacebookLikeView didFailLoadWithError:(NSError *)error
{
    NSLog(@"FacebookLikeView error: %@",error);
}

With this, I can see the like button, able to login into the browser, but then nothing will happen! It will just show Like button every time!

This was working good with old SDK FBConnect, the problem is with latest Facebook SDK, you can find the FacebookLikeView here,

What I'm missing?


Solution

  • Big Update !

    If you're seeing this that means, now you don't need to patch (or hack) anything to support like (a page on Facebook or any Open Graph object) in your application. With latest release for Facebook iOS SDK (FacebookSDK.framework) they're supporting like button, however (while I'm writing this update) its in beta, but we've something that we're wished from a long time, thank you Facebook.

    Here's the direct link for the change log and like button and yes documentation too.

    Solution: [RECOMMENDED]

    The Like button can be used to like a Facebook Page or any Open Graph object and can be referenced by URL or ID. Here's what the code looks like:

    FBLikeControl *like = [[FBLikeControl alloc] init];
    like.objectID = @"http://shareitexampleapp.parseapp.com/photo1/";
    [self addSubview:like];
    

    enter image description here

    (Source : Documentation).


    Old school way [NOT RECOMMENDED]

    Finally, I'm able to solve my problem, I'm putting solution steps so it will really helpful to someone who's looking for this kind of stuff,

    Some things you may need to know (from my question)

    • I'm using FBConnect and Facebook SDK at the same time in my app.
    • Both are working fine, FBConnect is only for FacebookLikeView -- You need to replace FBRequest class with some other name into FBConnect so it will not conflict with the latest SDK.
    • Still need for some easy and quick solution as this is not the perfect solution.

    So here we go,

    How do you get to know whether this particular page is liked by the user or not ?

    You need to use the Graph API with and check the User's likes. Here is an example.

    https://graph.facebook.com/{USER_ID}/likes/{PAGE_ID}
    

    If the user likes the page in question, it will return JSON looking like this if the user likes the page.

    {
      "data": [
        {
          "name": "SomeCafe", 
          "category": "Restaurant/cafe", 
          "id": "someIdWillCome", 
          "created_time": "2013-05-07T12:32:00+0000"
        }
      ], 
      "paging": {
        "next": "https://graph.facebook.com/me/likes/someIdWillCome?format=json&limit=5000&offset=5000&__after_id=someIdWillCome"
      }
    }
    

    And like this if the user doesn't like the page:

    {
      "data": [
      ]
    }
    

    Here's the documentation on User likes: https://developers.facebook.com/docs/reference/api/user/#likes

    Implementation

    1) Implement FacebookLikeView as given on its docs.

    2) I need to implement one HTTP request to call above URL to check the current status for that page as I couldn't get it from FacebookLikeView. Remember, you need to do GET request along with access_token.

    3) Check into the response (close to above example) and do the things as you need!

    That's it!

    Here's the solutions for FacebookLikeView issues I faced


    1) FacebookLikeView went away somewhere?

    Its because a comment popover hides it! below is the solution

    In FacebookLikeView.m class look for, - (void)didObserveFacebookEvent:(NSString *)fbEvent And add these lines in the end,

    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0f)
    {
        //NS_AVAILABLE_IOS(5_0);
        [[_webView scrollView] setContentOffset: CGPointMake (0, 0)];
    }
    

    2) FacebookLikeView shows UIKeyboard!!

    It's because of the comment text box focus after like a page, below is solution for that.

    - (void) keyboardWasShown:(NSNotification *)notification
    {
        //force hide UIKeyBoard
        [self.view endEditing:YES];
    }
    

    Added notification into viewDidLoad into class where you implementing

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    

    This will resign all keyboard visible from that particular view, in my case I'd no UITextField where I need the Facebook Like Button, so if your case is difference then make sure with this point.

    3) The slow loading issue is depends on many things Facebook server, Internet connection or something else, so I added a loading indicator into it -- It takes some time but working as I want!.


    This will allow me like / unlike a Facebook page also I am able to know the current status of that particular user so I can decide what to do!

    At last, thanks everyone who checked this issue and respond me! Appreciated! :)