iOS Programming 101: Integrate Twitter and Facebook Sharing in Your App

160 Flares 160 Flares ×

Following the Twitter support in iOS 5, Apple added the support of Facebook in iOS 6. In the past, developers have to make use of the Facebook and Twitter API to integrate the sharing feature in their apps. With the built-in support, it’s much easier to add these social features to your own app.

In this short tutorial, we will show you how to build Twitter and Facebook sharing feature in your app. As usual, we’ll build a simple app together as we believe there is no better way to teach programming than “get your hand dirty”.

Social Framework in iOS 6

The iOS 6 introduces a new framework known as the “Social Framework”. The Social framework lets you integrate your app with any supported social networking services. Presently, it supports Facebook, Twitter and Sina Weibo. The framework gives you a standard interface to interact with different social networks and it shields you from learning the internals. You don’t have to worry about the Twitter/Facebook APIs, how to handle network connection, handle single sign-on, etc. The social framework simplifies everything. You just need to write a few lines of code to bring up the composer and users can tweet / publish Facebook post within your app.

The framework comes with a very handy class named SLComposeViewController. The SLComposeViewController class presents a standard view controller for users to compose tweet or Facebook post. It also allows developers to preset the initial text, attach images and add URL to the post. If you just want to implement simple sharing feature, this is the only class you need to know and that we will go through today.

If you’re not familiar with the SLComposeViewController, this is what it looks like within your app.

User Interface for Twitter and Facebook in Your App

User Interface for Twitter and Facebook in Your App

Now you should have a basic idea about the framework. Let’s get started and build a simple app with Twitter and Facebook integration.

Create the Project and Design the Interface

As you need to use iOS 6 for this tutorial, please upgrade your Xcode to v4.5 or up before proceeding.

First, create a new Xcode project using the Single View Template. Let’s name the project as “SocialSharing” and set the project with the following parameters:

SocialSharing Xcode Project

SocialSharing Xcode Project

Once you’ve successfully created your project, go to the Storyboard and design the user interface. In the view, add two buttons. Name one as “Tweet” and the other one as “Facebook”.

SocialSharing App Interface Design

Designing the interface for the App

Establish the Connection Between Variables and UI Elements

Next, we’ll connect the UI elements with our code. In the Storyboard, select the view controller and switch to the Assistant Editor.

Show Assistant Editor

Show Assistant Editor and Hide Utility Area

Press and hold the control key, click the “Tweet” button and drag it towards the “SocialSharingViewController.h”. Create an action method and name it as “postToTwitter”. This method will be invoked when the button detects a Touch Up Inside event.

SocialSharing App Add Action Method

Add action methods for both Tweet and Facebook buttons

Repeat the same procedures the “Facebook” button and name the action method as “postToFacebook”. Below is the final code for “SocialSharingViewController.h”:

1
2
3
4
5
6
7
#import <UIKit/UIKit.h>

@interface SocialSharingViewController : UIViewController
- (IBAction)postToTwitter:(id)sender;
- (IBAction)postToFacebook:(id)sender;

@end

Adding Twitter Support

Let’s first start with the implementation of “postToTwitter” method. Open the “SocialSharingViewController.m” and add the following code for the “postToTwitter” method:

1
2
3
4
5
6
7
8
9
- (IBAction)postToTwitter:(id)sender {
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
    {
        SLComposeViewController *tweetSheet = [SLComposeViewController
                                               composeViewControllerForServiceType:SLServiceTypeTwitter];
        [tweetSheet setInitialText:@"Great fun to learn iOS programming at appcoda.com!"];
        [self presentViewController:tweetSheet animated:YES completion:nil];
    }
}

As “SLComposeViewController” is a class provided by the Social framework, remember to import the Social.h file at the very top of the “SocialSharingViewController.m”:

1
#import <Social/Social.h>

Before we move on, let’s take a look at the above code line by line.

Line #2 – Firstly, we use the “isAvailableForServiceType” method to verify if the Twitter service is accessible. One reason why users can’t access the Twitter service is that they haven’t logged on the service in the iOS.

Line #4 – If the service is accessible, we then create an instance of the SLComposeViewController for the Twitter service.

Line #5 – We set the initial text in the composer.

Line #6 – Finally, we invoke presentViewController:tweetSheet to bring up the Twitter composer.

That’s the code we need to let user tweet within your own app. It’s much easier than you thought, right? But we still miss one thing before the app can be run.

By default, the Social framework is not included in the Xcode project. To compile the app properly, add the “Social.framework” in the project. In the Project Navigator, select the “SocialSharing” project. In the Content Area, select “SocialSharing” under Targets and click “Build Phases”. Expand “Link Binary with Libraries” and click the “+” button to add the “Social.framework”.

SocialSharing Add Social Framework

Add Social framework to the project

Now, it’s ready to test the app. Click the “Run” button to try out the app in Simulator. When the app is launched, tap the “Tweet” button and you should see a similar screenshot as below:

SocialSharing Twitter App

Testing the Tweet Feature

In case you haven’t registered your Twitter account in the Simulator, you’ll end up with the below. Just go to Settings -> Twitter and sign on with your Twitter account.

SocialSharing Twitter Account Error

You haven’t registered your Twitter account in iOS

Adding Facebook Support

Next, we’ll implement the button for publishing wall post on Facebook. In the “SocialSharingViewController.m”, add the following code in the “postToFacebook” method:

1
2
3
4
5
6
7
8
- (IBAction)postToFacebook:(id)sender {
    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
            SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
       
        [controller setInitialText:@"First post from my iPhone app"];
        [self presentViewController:controller animated:YES completion:Nil];        
    }
}

That’s it. The code is very similar to the code we’ve used in the “postToTwitter” method. The only change is the service type. Instead of using SLServiceTypeTwitter, we tell SLComposeViewController to use SLServiceTypeFacebook.

Let’s run the app again and click the “Facebook” button. Your app should bring up the composer for publishing Facebook post.

SocialSharing App Facebook Post

Adding Image and Link to Your Post

Wouldn’t be great to upload your post with image and link? The SLComposeViewController comes with some built-in methods to allow you easily do the upload. Let’s tweak the code of the Facebook button and make the upload work.

First, download this image and add it to the Xcode project. (You can use any image but make sure you name it as “socialsharing-facebook-image.jpg”)

You can simply use the “addImage” method to attach an image and the “addURL” method to include a link.

1
2
        [controller addURL:[NSURL URLWithString:@"http://www.appcoda.com"]];
        [controller addImage:[UIImage imageNamed:@"socialsharing-facebook-image.jpg"]];

The final code for “postToFacebook” should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
- (IBAction)postToFacebook:(id)sender {
    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
       
        SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
       
        [controller setInitialText:@"First post from my iPhone app"];
        [controller addURL:[NSURL URLWithString:@"http://www.appcoda.com"]];
        [controller addImage:[UIImage imageNamed:@"socialsharing-facebook-image.jpg"]];
       
        [self presentViewController:controller animated:YES completion:Nil];
       
    }
}

Go ahead to run the app and test out the Facebook feature again. You should see a thumbnail and a link bundled in the post.

SocialSharing Facebook Post with Image

Upload Post with image and link

Summary

As you can see from this tutorial, it’s pretty easy to add Twitter and Facebook feature using the Social Framework in iOS 6. If you’re building your app, there is no reason why you shouldn’t incorporate the social features. With Twitter and Facebook support, it adds values to your app and may boost its popularity.

The tutorial introduces the basics of Facebook and Twitter integration. You can try to tweak the demo app and upload multiple images to the social networks. However, if you want to access more advanced features such as display users’ Facebook friends, you’ll need to study the Facebook API.

I hope you enjoy the tutorial and you have a better understanding about the social framework. Feel free to leave your questions and share your thought about the tutorial.

You May Like These:

Get Free Chapters of Our Swift Book

Beginning iOS 8 Programming with SwiftIf you want to create an app but don't know where to begin, this book covers the whole aspect of Swift programming and iOS 8 development and shows you every step from an idea to a real app on App Store. This book features a lot of hands-on exercises and projects. You will first create a simple app, then prototype an app idea, and later add some features to it in each chapter, until a real app is built. Want to learn more? Check it out here and get three free chapters.


  • Toby Powell

    as always, brilliant! you make concepts simple and clear to understand. Your blog rocks! thank you

    • http://www.simonblog.com Simon Ng

      Thanks for your support!

  • Dony Purnama

    haahaha keep rocking with the tutorial

  • Pingback: iOS Programming: Integrate Twitter and Facebook Sharing in iOS 6 … | MUSCLE CODER()

  • wordgeist

    do you know to implement the facebook like button?

  • Nagababu

    thanks for ur code..it is very useful for learners

  • Vandana

    It was very easy to understand but I faced one problem. In case of facebook if user has not logged in through twitter it does not redirects to settings so that user can login. The setting button actually takes us back to first screen.

  • Podster

    Great tutorial. Is there anyway to show a Facebook sample on how to post multiple images to the same wall post?

  • muckel_buckel

    The Facebook doesn’t go on my Device(iphone 5)
    When i click on the button Facebook, he show nothing, but the twitter button work perfect.

    Pleas help

    • http://www.simonblog.com Simon Ng

      Does it show any error in console?

  • Roy

    I need to display my app name in place of ios how can it be done ??

  • Shinalboma

    I’m trying the sharing to facebook part for my app. It’ll work if the app is on my iPhone. I’m using the simulator now and I think may need to have more code for facebook login. I’m checking with the facebook sdk tutorial now.

  • Podster

    I also would love to know how to replace the photo album name from iOS Photos to my App Name…

  • Emil

    Thank you so much!!

  • Pingback: Link your appli to facebook()

  • Andy

    Is there anyway to tweet to someone specific? So if I have 2 different view controllers with 2 different tweet buttons for 2 different profiles of people, can I tweet to them specifically when the user clicks on their profile in my app? Thank you

  • GD

    How we can hide the keyboard in both facebook and twitter post window.

  • ashokdy

    Please help in uploading and downloading the files to and from the iPhone sdk

  • http://www.facebook.com/jasmin.shikalgar Jasmin Shikalgar

    Twitter limit of 140 characters per tweet. It becomes extremely hard especially when try to share a big tweet. Is there any way to Tweet More Than 140 Characters?

  • Steve

    Neither the image or the link is showing up? Help! Will any image work or does it need to sized to fit?

    • steve

      Wow….nevermind….I get it

  • Steve

    Ok, scratch that…still not working. Help!

  • Sabre

    The Facebook doesn’t go on my Device(iphone 4)
    When I tapped on the button Facebook, it didn’t show anything without any error message, but the twitter button work perfect.
    When I tested this on simulator it’s works fine but not on my device(iphone 4).
    Pleas tell me the reason why it happens….

    • http://www.simonblog.com Simon Ng

      What version of iOS are you using on iPhone? Facebook sharing only works on iOS 6 (or up).

      • Sabre

        iOS 6.1.3

        • clive dancey

          HI
          Did you ever solve this problem..i have the same issue..twitter is fine in the simulator but wont work on the phone !!!…aaaagh…driving me mad..any help you have would be awesome.
          thanks

          • Sabre

            If you set the deployment target under iOS 6, then uncheck “Autolayout” in “the file inspector” of the storyboard.

        • jojo

          try to go to setting and configure your Facebook account there then try again. works with me

  • clive dancey

    hi
    This is great in the simulator but wont work on my Iphone running 6.1..any ideas..
    thanks

  • hitesh

    nice

  • lolo

    Same problem

    please any solution

    why this message keeps appearing to me?

    2013-06-25 11:50:39.885 app[1255:19703] Warning: Attempt to present on whose view is not in the window hierarchy!

    Thank you

  • Pingback: integerating twitter,facebook to iphone app using button is not working | BlogoSfera()

  • Raft Tone

    Thank you! Helped a lot!

  • Kai Bfm

    Facebook sharing do not work in iOS 6.1 :( . How to fix this problem ?

    • http://www.simonblog.com Simon Ng

      What’s the error you’re experiencing?

  • Kai Bfm

    it don’t work on my device ( Iphone 4 IOS 6.1.3 ). When I debugged , code did not run this condition

    if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {

    }

    Pleas tell me the reason why it happens.

    • vikas singh

      remove this line

      if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {

      and run the code .it will work :)

  • ich

    Great tutorial! Thanks a lot!

  • ShanghaiTimes

    Brilliant stuff guys.
    Can we add Weibo as well.
    .. and can we have some iOS 7 tutorials as well. The interface is actually quite different, in Xcode 5. But this Twitter tutorial goes in without much pain :-)
    If I would just learn to spell peroperly

  • Pingback: Xcode 4.6.3+OpenCV开发iOS应用 | 邓安良的网络日志()

  • braden

    Why the app doesn’t show up “No Twitter Account” or “No Facebook Account” alert view in iOS simulator???

  • karmjit

    nice article… visit my blog and please provide feedback..https://www.facebook.com/learniosprogramming

  • Pingback: share it button doesn't work ios 7 xcode 5 | BlogoSfera()

  • Vicky Mathneja

    @Roy u have to use Facebook SDK and make an appID by registering your app in Facebook

  • Jacopo

    Facebook and twitter sharing doesn’t work on iOS 7… the same script on ios 6 work…

    • Pavan

      What is the solution for this?

  • Pingback: Instagram framework for iOS | BlogoSfera()

  • Hareesh

    This code doesn’t works,will u please source code

  • Pingback: share it button doesn’t work ios 7 xcode 5 | Ask & Answers()

  • Goran

    hi! Question: Is there a way to post to FB without prompting the user? Could you make a tutorial about that?

  • Guest

    hi! Question: Is tehere a way to post to FB without promting the user? Could you make a tutorial about that?

  • NissiVM

    Thank you so much for this tut! =]

  • Pingback: FB and Twitter Integration | Stackforum.com()

  • LN Fanning

    Hi there! This code has been very very useful. Thank you. I have successfully integrated fb and twitter sharing on my photo booth app. However, I am having trouble adding the image that has just been edited and saved to photo library to the tweet/fb post. What should I add in controller addImage:____? Can you help me please? Here is the code just before the (IBAction)postToTwitter:(id)sender code I added >>>.

    – (IBAction)save:(id)sender {
    _topBar.hidden = YES;

    _bottomBar.hidden = YES;
    for (A4WRotateImage *view in self.view.subviews) {
    if ([view isKindOfClass:[resizableSticker class]]) {
    [view hideEditingHandles];
    }
    }

    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);

    if ([self.view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {

    [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];

    NSLog(@”RUN iOS 7″);
    }
    else
    {
    NSLog(@”RUN iOS 6″);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    }

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    _topBar.hidden = NO;
    _bottomBar.hidden = NO;

    for (UIView *view in self.view.subviews) {
    if ([view isKindOfClass:[resizableSticker class]]) {
    [view removeFromSuperview];
    }
    }
    _mainImage.image = image;

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

    UIAlertView *saved = [[UIAlertView alloc]initWithTitle:@”Success!” message:@”Photo saved to Camera Roll.” delegate:self cancelButtonTitle:@”Ok” otherButtonTitles:nil, nil];
    [saved show];

    [[RevMobAds session]showFullscreen];
    }

  • john carter

    How to show the success message after posting it to twitter/facebook, what is the property/method that we need to refer.

  • CreativeApps LLC

    Can this be used to post to another user’s wall or to a product page etc..

  • ever21

    Thanks for posting this!

  • roeland

    is it also possible to add a url to an image. so when you click in Facebook on the image, you will open safari or something on your phone? now we see the url as a text…

  • Raushan Kumar

    How can we authenticate facebook from our IPhone application using OAuth Protocol?

  • Robert Bojor

    Works like a charm! Thanks for the article.

    An additional thing you might consider is putting the addURL: and the addImage: inside an if statement, just in case they are not added ( both methods return a BOOL ) you can append the link to the end of the message. Ex: if ([tweetSheet addURL:[NSURL URLWithString:messageURL]]) { … } else {….}

    Thanks again for the article.

  • Victor

    Some times tweet is failing “Because last one was same as current one.”! How can we track this while using SLComposeViewController?

  • Pingback: Wie heeft ervaring met Social Framework? - iCulture forum | iPhone, iPad, iPod touch, Apple TV en iOS()

  • Pingback: spray tan or fake tan()

  • NIkita

    thanks!

  • Pingback: Facebook Login ios 6()

  • Pingback: Twitter integration in Swift()

  • Pingback: login twitter ios 6()

  • Pingback: ios 6 login with twitter()

  • Pingback: facebook login ios 6 tutorial()

  • Pingback: iOS Programming 101: Integrate Twitter and Facebook Sharing in Your App | jolam()

160 Flares Twitter 30 Facebook 112 Google+ 17 LinkedIn 1 160 Flares ×