Sunday 3 March 2013

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 orrelease 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.

No comments:

Post a Comment