Facebook 3.2 Invite Friend

This post is in continuation of my this answer at StackOverflow. Here is somewhat how it looks like:

FBDialog

 

First of all create a helper class called `FBHandler`.

Header File:

//
// FBHandler.h
// IntegrateFacebookInvite
//
// Created by Shahan on 04/09/2014.
// Copyright (c) 2014 Shahan. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <FacebookSDK/FacebookSDK.h>

@protocol FBDelegate

@required

-(void) OnFBSuccess;
-(void) OnFBFailed : (NSError *)error;

@end

@interface FBHandler : NSObject
{
NSInvocation *_callback;
}

@property (nonatomic, weak) id fbDelegate;

-(void)inviteFriends;

@end

Method File:

//
//  FBHandler.m
//  IntegrateFacebookInvite
//
//  Created by Shahan on 04/09/2014.
//  Copyright (c) 2014 Shahan. All rights reserved.
//

#import "FBHandler.h"

@implementation FBHandler

@synthesize fbDelegate;

-(void)inviteFriends
{
    if ([[FBSession activeSession] isOpen])
    {
        NSMutableDictionary* params =  [NSMutableDictionary dictionaryWithObjectsAndKeys:nil];
        [FBWebDialogs presentRequestsDialogModallyWithSession:nil
                                                      message:[self getInviteFriendMessage]
                                                        title:nil
                                                   parameters:params
                                                      handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
         {
             if (error)
             {
                 [self requestFailedWithError:error];
             }
             else
             {
                 if (result == FBWebDialogResultDialogNotCompleted)
                 {
                     [self requestFailedWithError:nil];
                 }
                 else if([[resultURL description] hasPrefix:@"fbconnect://success?request="])
                 {
                     // Facebook returns FBWebDialogResultDialogCompleted even user
                     // presses "Cancel" button, so we differentiate it on the basis of
                     // url value, since it returns "Request" when we ACTUALLY
                     // completes Dialog
                     [self requestSucceeded];
                 }
                 else
                 {
                     // User Cancelled the dialog
                     [self requestFailedWithError:nil];
                 }
             }
         }
         ];
        
    }
    else
    {
        /*
         * open a new session with publish permission
         */
        [FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:@"publish_stream"]
                                           defaultAudience:FBSessionDefaultAudienceFriends
                                              allowLoginUI:YES
                                         completionHandler:^(FBSession *session, FBSessionState status, NSError *error)
         {
             if (!error && status == FBSessionStateOpen)
             {
                 NSMutableDictionary* params =   [NSMutableDictionary dictionaryWithObjectsAndKeys:nil];
                 [FBWebDialogs presentRequestsDialogModallyWithSession:nil
                                                               message:[self getInviteFriendMessage]
                                                                 title:nil
                                                            parameters:params
                                                               handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
                  {
                      if (error)
                      {
                          [self requestFailedWithError:error];
                      }
                      else
                      {
                          if (result == FBWebDialogResultDialogNotCompleted)
                          {
                              [self requestFailedWithError:nil];
                          }
                          else if([[resultURL description] hasPrefix:@"fbconnect://success?request="])
                          {
                              // Facebook returns FBWebDialogResultDialogCompleted even user
                              // presses "Cancel" button, so we differentiate it on the basis of
                              // url value, since it returns "Request" when we ACTUALLY
                              // completes Dialog
                              [self requestSucceeded];
                          }
                          else
                          {
                              // User Cancelled the dialog
                              [self requestFailedWithError:nil];
                          }
                          
                      }
                  }];
             }
             else
             {
                 [self requestFailedWithError:error];
             }
         }];
    }
    
}

- (void)requestSucceeded
{
    NSLog(@"requestSucceeded");
    id owner = [fbDelegate class];
    SEL selector = NSSelectorFromString(@"OnFBSuccess");
    NSMethodSignature *sig = [owner instanceMethodSignatureForSelector:selector];
    _callback = [NSInvocation invocationWithMethodSignature:sig];
    [_callback setTarget:owner];
    [_callback setSelector:selector];
    
#if !__has_feature(objc_arc)
    [_callback retain];
#endif
    
    [_callback invokeWithTarget:fbDelegate];
}

- (void)requestFailedWithError:(NSError *)error
{
    NSLog(@"requestFailed");
    id owner = [fbDelegate class];
    SEL selector = NSSelectorFromString(@"OnFBFailed:");
    NSMethodSignature *sig = [owner instanceMethodSignatureForSelector:selector];
    _callback = [NSInvocation invocationWithMethodSignature:sig];
    [_callback setTarget:owner];
    [_callback setSelector:selector];
    [_callback setArgument:&error atIndex:2];
    
#if !__has_feature(objc_arc)
    [_callback retain];
#endif
    
    [_callback invokeWithTarget:fbDelegate];
}

-(NSString *)getInviteFriendMessage
{
    return @"I found this app amazing and would like you to join as well.";
}

@end

and this is how one can consume it:

//
//  ViewController.m
//  IntegrateFacebookInvite
//
//  Created by Shahan on 04/09/2014.
//  Copyright (c) 2014 Shahan. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    // Instatiate it
    fbHandler = [[FBHandler alloc] init];
}

#pragma mark - FBHandler delegate functions

-(void)OnFBSuccess
{
    NSLog(@"successful");
}

-(void)OnFBFailed:(NSError *)error
{
    if(error == nil)
        NSLog(@"user cancelled");
    else
        NSLog(@"failed");
}

#pragma mark - Event Handlers

-(IBAction)btnInviteFriend_Click:(id)sender
{
    [fbHandler setFbDelegate:self];
    [fbHandler inviteFriends];
}

@end

and this is how where the button of invite friends were setup in view controller:

main screen

Source Code:

Here are the source files for FBHandler

Advertisements

One thought on “Facebook 3.2 Invite Friend

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s