Saturday, 13 October 2012

integrating facebook and twitter in iOS 6 Apps (Social Framework)

Hello friends!! In this post, i am going to talk about social framework(introduce in iOS6). How to integrate facebook or twitter in iOS6 App.
        Social framework is introduce in iOS6 and by using it we can connect to facebook, twitter or weibo.com, no need of any third party SDKs. To learn social framework in iOS6 you should have Xcode 4.5. Lets start without wasting time first create a single view application and design your first screen as following screen -

Now add Social framework to your project - 
  1. Click on project name in project navigator
  2. Select the project under target in middle pan of Xcode
  3. Make sure that "Build Phases" tab is selected
  4. Expand the "Link binary with libraries", click on triangle
  5. Click on add item(+ button) in left corner of this section 
  6. Search social in search bar (comes after clicking on + button)
  7. Select the "Social.framework" framework and click on "Add" button 

Cheers you have completed the first step of this tutorial. Now import the social framework header file "Social.h" in ViewController.h file of your project.
// import social header file
 #import<Social/Social.h>

Add following two methods to "ViewController.h" file and connect them to respective button's touch event in respective view controller.
 //called on tap of facebook button
 - (IBAction)postOnFacebookButtonTapped:(id)sender;
 //called on tap of tweet button 
 - (IBAction)tweetButtonTapped:(id)sender;


Similarly add body of these two methods in "ViewController.m" file
- (IBAction)postOnFacebookButtonTapped:(id)sender {
}

- (IBAction)tweetButtonTapped:(id)sender {
}


We have added the required framework and methods to our project now it is the time to write the actual code. Social framework provides built in composer (SLComposeViewController), which we can pressent to user with pre loaded text, URL, and images so that user can tweet or post on their timeline. To present the composer we need to create an instance of this class. We can not edit or add any thing to the composer without informing the user. So we must add any initial content before presenting the composer to the user. After presenting the composer, only user can edit the content. 
        
+(SLComposeViewController*)composeViewControllerForServiceType:(NSString*) serviceType  

Above method is use to create the instance of SLComposeViewController and for it we need to pass service type. Service type tells the targeted social website like facebook, twitter and weibo. Service types are as follows -
  • SLServiceTypeTwitter
  • SLServiceTypeFacebook
  • SLServiceTypeSinaWeibo 
You should pass desire service type to create the respective composer. Before creating or presenting the composer we should check the availability of service type  or reachability of site. For this we can use following class method - 

+ (BOOL)isAvailableForServiceType:(NSString *)serviceType

This methods returns BOOL value where NO represents one of following - 
  1. User's twitter or facebook account is not set up on device
  2. Desire site is  not available 
Now lets implement postOnFacebookButtonTapped: method 
- (IBAction)postOnFacebookButtonTapped:(id)sender {
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        SLComposeViewController *fbComposer = [SLComposeViewController
                                               composeViewControllerForServiceType:SLServiceTypeFacebook];
        //set the initial text message
        [fbComposer setInitialText:@"Hi i am coding for bugs!!"];
        //add url
        if ([fbComposer addURL:[NSURL URLWithString:@"www.kmithi.blogspot.com"]]) {
            NSLog(@"Blog url added");
        }
        
        
        // you can remove all added URLs as follows
        //[fbComposer removeAllURLs];
        
        //add image to post
        if ([fbComposer addImage:[UIImage imageNamed:@"strongBinary"]]) {
            NSLog(@"strong binary added to the post");
        }
        if ([fbComposer addImage:[UIImage imageNamed: @"scan.jpg"]]) {
            NSLog(@"scan is added to the post");
        }
        
        //remove all added images
        //[fbComposer removeAllImages];
        
        //present the composer to the user
        [self presentViewController:fbComposer animated:YES completion:nil];
        
    }else {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"Facebook Error"
                                  message:@"You may not have set up facebook service on your device or\n                                  You may not connected to internent.\nPlease check ..."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles: nil];
        [alertView show];
    }
}


Yah!! It is this much easy any one can add facebook and twitter to their applications. All methods use to set initial text or add/ remove URLs and images returns BOOL values  where YES tells that successfully added/ removed image or URL.  You can add more than one image but not URL only last URL will be posted to your timeline. If your account is not set up then first set up it (Settings --> facebook) otherwise it will returns NO while checking the availability of service or error while posting. Similarly we can implement  tweetButtonTapped: method-
- (IBAction)tweetButtonTapped:(id)sender {
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
        
        SLComposeViewController *twitterComposer = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
        
        //add initial text
        [twitterComposer setInitialText:@"Tweeting from iPhone 5 #TesingApp"];
        
        //present composer
        [self presentViewController:twitterComposer animated:YES completion:nil];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"twitter Error"
                                  message:@"You may not have set up twitter service on your device or\n                                  You may not connected to internent.\nPlease check ..."
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles: nil];
        [alertView show];
    }
}


Composer view controllers looks like follow -





















Now i am going to discussed the last but not least feature of SLComposeViewController class. It is the completion handler. SLComposeViewController class define a block property of type SLComposeViewControllerCompletionHandler. SLComposeViewControllerCompletionHandler takes a parameter of type SLComposeViewControllerResult. Parameter indicate wether user finished or cancelled composing the post. Parameter will be one of following - 
  • SLComposeViewControllerResultCancelled,
       It indicates  that user has cancelled composing the post
  •  SLComposeViewControllerResultDone
       It indicates  that user has finished composing the post 
 //add completion handler
        twitterComposer.completionHandler = ^(SLComposeViewControllerResult result) {
            if (result == SLComposeViewControllerResultCancelled) {
                NSLog(@"User has cancled composing the post, and tapped the cancle button");
            }
            
            if (result == SLComposeViewControllerResultDone) {
                NSLog(@"User has finished composing the post, and tapped the send button");
            }
        };


To know more about block programming check this!
Thanks for reading!! Please leave your valuable suggestions!! Bye Bye !!

6 comments:

  1. Excellent blog, With this much of elaboration.

    ReplyDelete
  2. Helped a lot and a very good blog as wel!!
    THank you!

    ReplyDelete
  3. Great tutorial. Is there any way you can automatically set the location of where a person is at?

    ReplyDelete
    Replies
    1. Sorry Daniel, I think there is no any method to do it ....

      Delete
  4. how can i share video ......ios6????

    ReplyDelete