2011年10月17日星期一

iOS 5 : Twitter Framework – Part 1

iOS 5 : Twitter Framework – Part 1:

This is the first post of two on how to work with the new Twitter framework in an iOS 5 app. This post will cover the basics to create and display a dialog for composing a tweet.


The primary controller for working with Twitter in iOS 5 is TWTweetComposeViewController. This object handles all the UI related work to display and manage input – you can pre-populate the initial text, add an image as well as a URL. The code is straight forward to get things rolling:



#import <Twitter/Twitter.h>

...

// Create the view controller
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];

// Optional: set an image, url and initial text
[twitter addImage:[UIImage imageNamed:@"iOSDevTips.png"]];
[twitter addURL:[NSURL URLWithString:[NSString stringWithString:@"http://iOSDeveloperTips.com/"]]];
[twitter setInitialText:@"Tweet from iOS 5 app using the Twitter framework."];

// Show the controller
[self presentModalViewController:twitter animated:YES];

// Called when the tweet dialog has been closed
twitter.completionHandler = ^(TWTweetComposeViewControllerResult result)
{
NSString *title = @"Tweet Status";
NSString *msg;

if (result == TWTweetComposeViewControllerResultCancelled)
msg = @"Tweet compostion was canceled.";
else if (result == TWTweetComposeViewControllerResultDone)
msg = @"Tweet composition completed.";

// Show alert to see how things went...
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil];
[alertView show];

// Dismiss the controller
[self dismissModalViewControllerAnimated:YES];
};


Notice the Objective-C block (more on blocks here) that is defined for the completion handler, this is called once the user has finished composing the tweet.


Before running the code you’ll need to configure a Twitter account. If you skip this step you’ll see the dialog on the left below. The image on the right is the settings screen to configure an account. Also, you will need to add the Twitter framework to your Xcode project before compiling.



The screenshot below shows the Twitter view controller poplated with the content shown above.



Below is a screenshot from the twitter page showing how the tweet above looks at twitter.com/iOSDevTips.



That’s all you need to get started for basic twitter integration. In the next post I’ll go into more detail including a look at the ACAccountStore for managing accounts and TWRequest for sending HTTP requests to Twitter.


没有评论:

发表评论