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.
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
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:
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”.
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.
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.
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”.
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:
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.
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.
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:@"https://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:@"https://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.
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.
Comments
Toby Powell
Authoras always, brilliant! you make concepts simple and clear to understand. Your blog rocks! thank you
Simon Ng
AuthorThanks for your support!
Dony Purnama
Authorhaahaha keep rocking with the tutorial
wordgeist
Authordo you know to implement the facebook like button?
Nagababu
Authorthanks for ur code..it is very useful for learners
Vandana
AuthorIt 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
AuthorGreat tutorial. Is there anyway to show a Facebook sample on how to post multiple images to the same wall post?
muckel_buckel
AuthorThe 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
AuthorDoes it show any error in console?
Roy
AuthorI need to display my app name in place of ios how can it be done ??
Amir Habib
AuthorDid you got any solution ???
marvingreen
Authoruse FBDialogs using FacebookSDK.framework
Shinalboma
AuthorI’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
AuthorI also would love to know how to replace the photo album name from iOS Photos to my App Name…
Emil
AuthorThank you so much!!
Andy
AuthorIs 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
AuthorHow we can hide the keyboard in both facebook and twitter post window.
ashokdy
AuthorPlease help in uploading and downloading the files to and from the iPhone sdk
Jasmin Shikalgar
AuthorTwitter 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
AuthorNeither the image or the link is showing up? Help! Will any image work or does it need to sized to fit?
steve
AuthorWow….nevermind….I get it
Steve
AuthorOk, scratch that…still not working. Help!
Sabre
AuthorThe 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
AuthorWhat version of iOS are you using on iPhone? Facebook sharing only works on iOS 6 (or up).
Sabre
AuthoriOS 6.1.3
clive dancey
AuthorHI
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
AuthorIf you set the deployment target under iOS 6, then uncheck “Autolayout” in “the file inspector” of the storyboard.
jojo
Authortry to go to setting and configure your Facebook account there then try again. works with me
clive dancey
Authorhi
This is great in the simulator but wont work on my Iphone running 6.1..any ideas..
thanks
hitesh
Authornice
lolo
AuthorSame 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
AuthorThank you! Helped a lot!
Kai Bfm
AuthorFacebook sharing do not work in iOS 6.1 🙁 . How to fix this problem ?
Simon Ng
AuthorWhat’s the error you’re experiencing?
Kai Bfm
Authorit 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
Authorremove this line
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
and run the code .it will work 🙂
ich
AuthorGreat tutorial! Thanks a lot!
ShanghaiTimes
AuthorBrilliant 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
AuthorWhy the app doesn’t show up “No Twitter Account” or “No Facebook Account” alert view in iOS simulator???
karmjit
Authornice article… visit my blog and please provide feedback..https://www.facebook.com/learniosprogramming
Vicky Mathneja
Author@Roy u have to use Facebook SDK and make an appID by registering your app in Facebook
Jacopo
AuthorFacebook and twitter sharing doesn’t work on iOS 7… the same script on ios 6 work…
Pavan
AuthorWhat is the solution for this?
Hareesh
AuthorThis code doesn’t works,will u please source code
Guest
Authorhi! Question: Is tehere a way to post to FB without promting the user? Could you make a tutorial about that?
Goran
Authorhi! Question: Is there a way to post to FB without prompting the user? Could you make a tutorial about that?
NissiVM
AuthorThank you so much for this tut! =]
LN Fanning
AuthorHi 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
AuthorHow to show the success message after posting it to twitter/facebook, what is the property/method that we need to refer.
CreativeApps LLC
AuthorCan this be used to post to another user’s wall or to a product page etc..
ever21
AuthorThanks for posting this!
roeland
Authoris 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
AuthorHow can we authenticate facebook from our IPhone application using OAuth Protocol?
Robert Bojor
AuthorWorks 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
AuthorSome times tweet is failing “Because last one was same as current one.”! How can we track this while using SLComposeViewController?
NIkita
Authorthanks!
Abhijit
Authorhow can i share my current location.
sazzadhusen iproliya
Authornice tutotrial…
but stiil one thing missing plaese attach photo frame select image.
nayan
AuthorThanks 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
AuthorMy image is coming from URL how i can post that image.
A_a
AuthorHow 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
Authorcan any one tell me! How to post the content of slcomposer without presenting dialog box. I mean click and share, no dialog box.
Claudio
AuthorHi 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
AuthorPlease find solution for Facebook video share here https://swiftoverflow.blogspot.in/2017/04/share-video-to-facebook.html