Friday, June 15, 2012

Facebook and Twitter integration in your iOS app

Hi Guys, Today I am showing you, how easily you can integrate Facebook and Twitter in your iOS application.

Let's first start with Facebook integration. For Facebook you have to register your app and you can register your app from here. Create you app there and enter basic information of your app as shown in below picture.  And note down your app Id.

Register your Facebook app

After registering app next step is to download latest Facebook iOS SDK from GitHub repository from here. Now move to Xcode. In your Xcode project add Facebook src files which you which download from GitHub repository. And Facebook integration is as below.

MDAppDelegate.h


#import <UIKit/UIKit.h>
#import "Facebook.h"

@class MDViewController;

@interface MDAppDelegate : UIResponder <UIApplicationDelegate,FBSessionDelegate, FBDialogDelegate>{
    
}

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, retain) Facebook *facebook;

@property (strong, nonatomic) MDViewController *viewController;

-(void)shareOnFB;

@end



MDAppDelegate.m



#import "MDAppDelegate.h"

#import "MDViewController.h"

@implementation MDAppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize facebook;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[MDViewController alloc] initWithNibName:@"MDViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [facebook handleOpenURL:url]; 
}

- (void)shareOnFB {
    self.facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID" andDelegate:self];
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"
        && [defaults objectForKey:@"FBExpirationDateKey"]) {
        self.facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        self.facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
    }
    
    
    if (![facebook isSessionValid]) {
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                @"user_likes"
                                @"read_stream",
                                nil];
        [self.facebook authorize:permissions];
        // [permissions release];
    }
}

#pragma mark Facebook Delegate Method

- (void) fbDidLogout {
    // Remove saved authorization information if it exists
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"]) {
        [defaults removeObjectForKey:@"FBAccessTokenKey"];
        [defaults removeObjectForKey:@"FBExpirationDateKey"];
        [defaults synchronize];
    }
}

- (void)fbDidLogin {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    
    [defaults synchronize];
    
    NSLog(@"facebook Integration : ");
    
    NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"YOUR_APP_ID", @"app_id",
                                   @"http://mandeepdhiman.blogspot.com", @"link",
                                   @"https://dl.dropbox.com/u/10137094/fb.png", @"picture",
                                   @"MyTestApp", @"name",
                                   @"Reference Documentation Text", @"caption",
                                   @"Facebook test integration from my App...", @"description",
                                   nil];
    
    [self.facebook dialog:@"feed" andParams:params andDelegate:self];
    
}


@end

One more thing you have to add in your application plist file "URL Schemes" for Facebook integration.  URL Schemes item value is 'fbYOUR_APP_ID'. As shown in image below.



Now we can move to Twitter Integration part. For twitter you have integrate your Twitter framework to you project and rest of the twitter integration is as below.

MDViewController.h

#import <UIKit/UIKit.h>
#import <Twitter/Twitter.h>

@interface MDViewController : UIViewController{
    
}
- (IBAction)shareOnTwitter:(id)sender;

@end

MDViewController.m

#import "MDViewController.h"
#import "MDAppDelegate.h"

@implementation MDViewController

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark -

- (IBAction)shareOnTwitter:(id)sender {
    
    TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
    
    [twitter addImage:[UIImage imageNamed:@"icon.png"]];
    [twitter addURL:[NSURL URLWithString:@"http://mandeepdhiman.blogspot.in"]];
    [twitter setInitialText:@"MyTestApp"];
    
    
    [self presentModalViewController:twitter animated:YES];
    
    twitter.completionHandler = ^ (TWTweetComposeViewControllerResult result){
        
        if (result == TWTweetComposeViewControllerResultDone) {
            NSLog(@"Tweet composition completed.");
        }else if ( result == TWTweetComposeViewControllerResultCancelled){
            NSLog(@"Tweet Composition was canceled.");
        }
        [self dismissModalViewControllerAnimated:YES];
    };
    
}

- (IBAction)shareFBBtnAction:(id)sender; {
    
    MDAppDelegate *appDelegate = ((MDAppDelegate *) [UIApplication sharedApplication].delegate);
    [appDelegate shareOnFB];
}

@end


App working video




You can download demo project from here

References
https://developers.facebook.com/docs/mobile/ios/build/
http://developer.apple.com/library/ios/#documentation/Twitter/Reference/TwitterFrameworkReference/_index.html

No comments:

Post a Comment