This tutorial was originally published in March 2011
This tutorial is going to be about adding a Twitter button to your app. By doing this you allow a user to tweet straight from your app rather than exiting and using another app. This became available in iOS 5, and it really is easy to do. Our app here is going to be very simple, but the steps to do this can be used in any app.
1.) Let’s start by creating a single view app.
Go ahead and name the app TwitterTutorial, we’ll use Automatic Reference Counting but will not be using a Storyboard.
2.) Before we do anything else let’s import the twitter framework. If you are unclear about how to do this you can check this tutorial.
Add a framework in Xcode 4 Tutorial
3.) Our view is going to be very simple. I’m going to spice it up just a little by changing the background and adding an image, but the main thing is to just add the button.
3.) Open up the view controller header file and declare an IBAction.
That’s all we have to do in the header file.
4.) Now open up the view controller implementation file and import Twitter.h.
5.) Next create implement the IBAction that we declared in the header file
//This creates the tweet view that we'll present modally when a user clicks the button.
TWTweetComposeViewController *tweetView = [[TWTweetComposeViewController alloc] init];
//You set a default tweet to show in the view
[tweetView setInitialText:@"Here's a tweet from your app"];
//You can tweet an image
[tweetView addImage:[UIImage imageNamed:@"twitter-logo.png"]];
//You can also add a link to the tweet
[tweetView addURL:[NSURL URLWithString:@"http://www.theappcodeblog.com"]];
// Specify a block to be called when the user is finished. This block is not guaranteed
// to be called on any particular thread.
// All we are doing is dismissing the modal view when the tweet is sent.
tweetView.completionHandler = ^(TWTweetComposeViewControllerResult result)
//present tweet view modally
[self presentModalViewController:tweetView animated:YES];
6.) Last thing is to hook up the IBAction to our button.
7.) And finally run the app.
Click the Tweet button and the Tweet view will open modally.
That’s it, here’s the code.