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.
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:@"http://roadfiresoftware.com/2014/02/how-to-add-facebook-and-twitter-sharing-to-an-ios-app/"]; UIImage *image = [UIImage imageNamed:@"roadfire-icon-square-200"]; UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:@[text, url, image] applicationActivities:nil]; [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
controller.excludedActivityTypes = @[UIActivityTypePostToWeibo, UIActivityTypeMessage, UIActivityTypeMail, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo, UIActivityTypeAirDrop];
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.)