iOS

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


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”:

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:

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”:

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:

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.

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

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.

iOS
MapKit Beginner’s Guide: Polylines, Polygons, and Callouts
iOS
How To Download Older Version of Xcode
iOS
Creating Simple Animations with Facebook’s Pop Framework
  • Toby Powell

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


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Thanks for your support!


  • Dony Purnama

    haahaha keep rocking with the tutorial


  • wordgeist

    wordgeistwordgeist

    Author Reply

    do you know to implement the facebook like button?


  • Nagababu

    NagababuNagababu

    Author Reply

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


  • Vandana

    VandanaVandana

    Author Reply

    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

    PodsterPodster

    Author Reply

    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


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Does it show any error in console?


  • Roy

    RoyRoy

    Author Reply

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


  • Shinalboma

    ShinalbomaShinalboma

    Author Reply

    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

    PodsterPodster

    Author Reply

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


  • Emil

    EmilEmil

    Author Reply

    Thank you so much!!


  • Andy

    AndyAndy

    Author Reply

    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

    GDGD

    Author Reply

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


  • ashokdy

    ashokdyashokdy

    Author Reply

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


  • 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

    SteveSteve

    Author Reply

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


    • steve

      stevesteve

      Author Reply

      Wow….nevermind….I get it


  • Steve

    SteveSteve

    Author Reply

    Ok, scratch that…still not working. Help!


  • Sabre

    SabreSabre

    Author Reply

    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….


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

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


      • Sabre

        SabreSabre

        Author Reply

        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

            SabreSabre

            Author

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


        • jojo

          jojojojo

          Author Reply

          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

    hiteshhitesh

    Author Reply

    nice


  • lolo

    lolololo

    Author Reply

    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


  • Raft Tone

    Raft ToneRaft Tone

    Author Reply

    Thank you! Helped a lot!


  • Kai Bfm

    Kai BfmKai Bfm

    Author Reply

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


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      What’s the error you’re experiencing?


  • Kai Bfm

    Kai BfmKai Bfm

    Author Reply

    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

    ichich

    Author Reply

    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


  • braden

    bradenbraden

    Author Reply

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


  • karmjit

    karmjitkarmjit

    Author Reply

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


  • Vicky Mathneja

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


  • Jacopo

    JacopoJacopo

    Author Reply

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


    • Pavan

      PavanPavan

      Author Reply

      What is the solution for this?


  • Hareesh

    HareeshHareesh

    Author Reply

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


  • Guest

    GuestGuest

    Author Reply

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


  • Goran

    GoranGoran

    Author Reply

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


  • NissiVM

    NissiVMNissiVM

    Author Reply

    Thank you so much for this tut! =]


  • LN Fanning

    LN FanningLN Fanning

    Author Reply

    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

    ever21ever21

    Author Reply

    Thanks for posting this!


  • roeland

    roelandroeland

    Author Reply

    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

    VictorVictor

    Author Reply

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


  • NIkita

    NIkitaNIkita

    Author Reply

    thanks!


  • Abhijit

    AbhijitAbhijit

    Author Reply

    how can i share my current location.


  • sazzadhusen iproliya

    nice tutotrial…
    but stiil one thing missing plaese attach photo frame select image.


  • nayan

    nayannayan

    Author Reply

    Thanks for tut! I have one question – After reviewing Facebook policies, they said not to pre-fill the dialogues while sharing on Facebook. So using this will violets rule!? So just want to clear on is it allowed or not?

    Please have a look at Facebook privacy policy link – https://developers.facebook.com/docs/apps/review/prefill


  • Ravish Kumar

    My image is coming from URL how i can post that image.


  • A_a

    A_aA_a

    Author Reply

    How can I change “Share on Facebook” self made button into button with Facebook icon image? Is it possible within the social framework, or do I need to download the images from somewhere else and create a custom button with image?


  • Anand Prakash

    can any one tell me! How to post the content of slcomposer without presenting dialog box. I mean click and share, no dialog box.


  • Claudio

    ClaudioClaudio

    Author Reply

    Hi there! I have a matter: when I am using a real device to post a text on Facebook, the setInitialText property does not fill with the text. Did someone solved this ? please help me to.


  • Reshma Nayak

    Please find solution for Facebook video share here http://swiftoverflow.blogspot.in/2017/04/share-video-to-facebook.html


Shares