Twitter Integration Tutorial

One of the exciting new features in iOS 5 is Twitter integration. Photos, YouTube, Safari, and Maps come fully integrated. With most iOS 5 users jumping on the Twitter bandwagon (Twitter daily signups tripled, according to Twitter’s CEO), allowing your users to tweet about your app could help put it in front of more people. In this iDevBlogADay post, I want to write a tutorial for integrating your app with Twitter.

Getting Started

Launch Xcode and create a new project. Select the Single View Application template as your starting point.

Leave project options as default. Make sure iPhone is selected for Device Family, and Use Storyboards and Use Automatic Reference Counting (ARC) are checked.

Add Twitter Framework

To take advantage of the Twitter framework, you must first add the it to your project:

Click on the project in the Navigator, select the project’s target, and switch to Build Phases. Then click on the arrow button next to Link Binary With Libraries. You should see a list of frameworks already included in the project. Now click on the + button and select Twitter.framework to add it to this list. The framework is designated as Required by default. Click on the text Required besides Twitter.framework and select Optional. Designating the Twitter framework as optional is necessary for supporting users running earlier versions of iOS.

Modify ViewController

Open ViewController.h and change its content to:

#import <UIKit/UIKit.h>
 
@interface ViewController : UIViewController
 
- (IBAction)tweetButtonPressed:(id)sender;
 
@end

We have just declared a new method tweetButtonPressed:. Open ViewController.m and add an import line at the top:

#import "Twitter/Twitter.h"

Then add the implementation for our new method above didReceiveMemoryWarning:

- (IBAction)tweetButtonPressed:(id)sender
{
    Class tweeterClass = NSClassFromString(@"TWTweetComposeViewController");
 
    if(tweeterClass != nil) {   // check for Twitter integration
 
        // check Twitter accessibility and at least one account is setup
        if([TWTweetComposeViewController canSendTweet]) {
            TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
 
            tweetViewController.completionHandler = ^(TWTweetComposeViewControllerResult result) {
                if(result == TWTweetComposeViewControllerResultDone) {
                    // the user finished composing a tweet
                } else if(result == TWTweetComposeViewControllerResultCancelled) {
                    // the user cancelled composing a tweet
                }
                [self dismissViewControllerAnimated:YES completion:nil];
            };
 
            [self presentViewController:tweetViewController animated:YES completion:nil];
        } else {
            // Twitter is not accessible or the user has not setup an account
        }
    } else {
        // no Twitter integration; default to third-party Twitter framework
    }
}

This method isn’t as complicated as it looks. Let’s go through it so we know what’s going on:

Class tweeterClass = NSClassFromString(@"TWTweetComposeViewController");
 
if(tweeterClass != nil) {   // check for Twitter integration
}

Do you remember that we designated the Twitter framework as optional? Backward compatibility is important since many users are not yet running iOS 5. But to do so, we must check for Twitter integration first. If the user is running an earlier iOS version, tweeterClass would be nil, and the method would safely return without crashing. Let’s continue onto the next if-block:

// check Twitter accessibility and at least one account is setup
if([TWTweetComposeViewController canSendTweet]) {
}

canSendTweet is a class method that returns YES if Twitter is reachable and at least one account is setup in Settings.app. Although you could just let iOS tell the users that they must setup an account first, checking canSendTweet allows us to customize the notice and enhance the users’ experience. Now we are ready to allocate and initialize the tweet compose sheet:

TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
 
// set initial text
[tweetViewController setInitialText:@"Check out tonyngo.net!"];
 
// add image
[tweetViewController addImage:[UIImage imageNamed:@"tweetImage.png"]];
 
// setup completion handler
tweetViewController.completionHandler = ^(TWTweetComposeViewControllerResult result) {
    if(result == TWTweetComposeViewControllerResultDone) {
        // the user finished composing a tweet
    } else if(result == TWTweetComposeViewControllerResultCancelled) {
        // the user cancelled composing a tweet
    }
    [self dismissViewControllerAnimated:YES completion:nil];
};
 
// present view controller
[self presentViewController:tweetViewController animated:YES completion:nil];

First we allocate the view controller. Notice anything unusual? There is no autorelease or release anywhere in this method. That’s because we’re taking advantage of iOS 5′s ARC mentioned previously. Next we set some initial text. If the text contains a URL, it would be shortened automatically. Then we add an image in the next line. You no longer need to worry about image hosts like Twitpic; the image will be uploaded directly to and hosted by Twitter (pic.twitter.com). After that, we setup the completionHandler. It’s a block defined as follow:

typedef void (^TWTweetComposeViewControllerCompletionHandler)(TWTweetComposeViewControllerResult result);

Blocks are only available in iOS 4, which means you cannot support earlier iOS versions. result is either TWTweetComposeViewControllerResultDone, if the user finished composing a tweet, or TWTweetComposeViewControllerResultCancelled, if the user cancelled composing a tweet. The view controller does not remove itself from the view stack, so we dismiss it with dismissViewControllerAnimated:completion. The parameter completion is new in iOS 5. It allows you to execute arbitrary code after the controller has been removed from view. Use nil if you don’t need it, like we did here. And finally, we present the view controller to the user.

Add Tweet Button

Open MainStoryboard.storyboard and drag a button control into the blank view controller. Double click on this button to rename its label to “Tweet.”

Now ctrl-drag the button to the View Controller below. A small popup menu will show up after you release the mouse button. Select tweetButtonPressed:. Save, and you’re done! Build and run the app and tweet something :)

Source Code

Source code may be downloaded here. If you find this tutorial useful, please tweet and +1 it below. Thank you :)

No related posts.

  • http://twitter.com/kohjingyu Koh Jing Yu

    Hey, you missed out importing in the view controller’s .h file :) Other than that good work!

    • Tony

      You are right. Thank you for pointing it out :) I’ll edit my post now.

  • http://twitter.com/FiveLakesStudio Five Lakes Studio

    Tony, thank you for a great article.  It was a good quick start to using Twitter in iOS 5.  I took your example and turned it into a little helper class for working with Twitter so I can send a tweet in a single line of code!  
        

        [[FLTwitter defaultManager] sendTweetFromViewController:self withText:@”Text to send with twitter goes here!”];I’m not switching all my code to use ARC yet, so the source I out together has to release objects.  The source is available here for anyone to use: http://bit.ly/FLTwitter  

    Thanks again,
    Tod

    • Anonymous

      Tod, this looks useful! Thanks for sharing :)

    • http://twitter.com/nawDsign Nor Sanavongsay

      Would this work in iOS 4.3?

      • http://www.facebook.com/kostiantyn.sokolinskyi Kostiantyn Sokolinskyi

        Never. Native Twitter integration is supported from iOS5.0

  • vince

    how I can add of the photos from the roll of film?

    • Anonymous

      From the “roll of film?”

      • vince

        sorry… from camera roll

  • Pingback: Happy iOS 5 Day! « Under The Bridge

  • http://www.noisetech-software.com/Home.html Steven Noyes

    Thanks for the sanity check.  I have added code that is very similar and it works kind of.  If I tweet only text, it works.  If use the AddImage: method, the send is disabled.  I have tried images from the camera roll, resource image files, JPEGs, PNGs, captures from the camera.  If I include any image, “Send” is simply disabled.

    Did you see anything like this?

    • Pradyumna

      Is this solved ?

  • http://openid.ericdsouza.com/ Eric D’Souza

    Great post!  This is one of the most clear tutorials I’ve read on any iOS topc!

  • suba

    Good one

  • http://twitter.com/sumitpaul Sumit Paul

    Thanks for this tutorial. I noticed there are memory leaks in it. Is something wrong with the twitter framework? … because I see leaks in Apple’s sample application as well.

    • Anonymous

      how did you test for memory leaks?

  • Pingback: iOS 5 SDK Tutorials | Best iPad Apps, Cases and Development

  • Pingback: iOS 5 SDK Tutorials

  • Tis

    its now work for me.
    when i run your example code, it shows tweet button…but nothing happen when i clicked it.

  • Ryan Powell

    You added the Twitter framework as optional. Yet you are directly referencing enums defined in the headers.

    Surely this would cause some problems for the compiler?

  • Chitopolo

    Thank you very much, was really helpful!

  • kirthika

    Thank u so much,its was awesome