How to add Facebook and Twitter sharing to an iOS app

Screen shot - Share on Facebook and Twitter

In iOS 6 and above, you can just use UIActivityViewController to allow the user to share on Facebook or Twitter. And, in fact, UIActivityViewController allows you to share or send data to several other services, like Mail, Messages, the Camera Roll, Reading List, Flickr, Vimeo, AirDrop, and more.

To use UIActivityViewController, you just need to pass some data to it (like text, a URL, or an image), then present the view controller. Here’s an example with all three:

NSString *text = @"How to add Facebook and Twitter sharing to an iOS app";
NSURL *url = [NSURL URLWithString:@""];
UIImage *image = [UIImage imageNamed:@"roadfire-icon-square-200"];

UIActivityViewController *controller =
[[UIActivityViewController alloc]
 initWithActivityItems:@[text, url, image]

[self presentViewController:controller animated:YES completion:nil];

So in the first three lines, we’re just creating the text string, URL, and image. Then we create an instance of UIActivityViewController, passing it our text, URL, and image. And then we present it.

If you want to exclude certain sharing activities – for example, if you only want the user to be able to share on Facebook and Twitter, you can do that with the excludedActivityTypes property on UIActivityViewController:

controller.excludedActivityTypes = @[UIActivityTypePostToWeibo,

And that’s it!

If you want to see the full sample code for this in a working app, it’s on GitHub. And if you want to learn more about UIActivityViewController, check out the docs – scroll to the bottom to see all the activity types you can use.

Enter your email below and grab my advice, tips, and tutorials on iOS development designed to help you become a master of iOS development – and never worry about whether your iOS chops are getting old, crusty, stale, and irrelevant again. (Or go back to maintaining legacy Java.)

You might also enjoy…

How to become a professional iOS developer

How I Reduced a View Controller by ~100 Lines (from 400 to 300)

Screencast: Testing Objective-C with the XCTest Framework