2011年11月5日星期六

Beginning Twitter in iOS 5 Tutorial

Beginning Twitter in iOS 5 Tutorial:
Enjoy some pan-seared Twitter in the iOS 5 Feast!
Enjoy some pan-seared Twitter in the iOS 5 Feast!

Note from Ray: This is the eleventh iOS 5 tutorial in the iOS 5 Feast! This tutorial is a free preview chapter from our new book iOS 5 By Tutorials. Enjoy!

This is a blog post by iOS Tutorial Team member Felipe Laso, an independent iOS developer and aspiring game designer/programmer.

These days, social networks are a huge part of our daily lives. Not only do we access social networks via their dedicated websites like twitter.com or facebook.com, but we also find social features in apps, websites, blogs, video games, and more.

Adding some social features into your apps can really help you increase the virality of your app, help you identify and retain customers, and can boost the polish and added value of your app.

Until now, adding social features into apps has been a pain. Not only do you have to use a different API for each social network, but users have to constantly log into each one of them for every app they use.

I can’t remember how many times I’ve had to log into Facebook or Twitter within a game or app. It can get quite tedious both as a developer and as a user to repeat the same thing over and over again for every application, up to the point where users won’t even bother because they don’t want to have to log on again.

Thankfully for us Apple has taken a huge step forward in this regard by having Twitter natively incorporated in iOS 5! Now all a user needs to do is log into Twitter once and each app can make use of your accounts stored on the device.

Keep reading to see how simple it is to use, and an example of integrating it into a simple app!



How Does It Work?


iOS 5 includes several ways to interact with Twitter. The simplest, and possibly the one you will most likely implement, is the TWTweetComposeViewController. That name is quite a handful so we will affectionately call it “Tweet Sheet” just as Apple does.

In this tutorial you will see that the tweet sheet is very easy to implement. With literally just a couple of lines you can have a full tweet composer within your app! You don’t have to worry about contacting the Twitter backend, handling user logins, or anything like that.

Here is a code snippet for creating and presenting the TWTweetComposeViewController:


if ([TWTweetComposeViewController canSendTweet])
{
TWTweetComposeViewController *tweetSheet =
[[TWTweetComposeViewController alloc] init];
[tweetSheet setInitialText:@"Initial Tweet Text!"];
[self presentModalViewController:tweetSheet animated:YES];
}


All you do is determine whether the device can send tweets, create an instance of the tweet sheet, attach any links or images, put some initial text and present it modally, that’s it! All within Xcode and through the use of Objective-C.

In fact it’s so easy, that if you’re an advanced developer you can just skip the rest of this tutorial and implement it yourself! But if you want to see an example of using “simple tweet” capability in a simple project, keep reading!

Overview


In this introductory Twitter tutorial we’ll cover the use of the TWTweetComposeViewController (i.e. the “tweet sheet”) which will enable us to tweet any text, image or link we want from within our applications. It looks something like this:

descr

The advantage of using the tweet sheet is that it’s built right onto iOS, this means lots of things:

  • Standard interface throughout the OS
  • Automatic use of the user’s system Twitter account
  • Automatic check for a tweet less than 140 characters long
  • Easy image and link attachments
  • Easy to program, no need to implement OAuth or connect to the Twitter backend

As you can see we have lots of advantages and incentives to use this and, being that it’s so simple, there’s no excuse not to include Twitter functionality in your applications!

Getting Started


Alright fellow programmers, it’s time to get our fingers typing and creating an awesome Twitter enabled app. In this example we’re going to create a simple app that will allow the user to tweet whatever text they like, and even include images or links within their tweet.

Create a new project with Xcode with the iOS\Application\Single View Application template. Enter SimpleTweet for the product name, set the device family to iPhone, and make sure that Use Storyboard and Use Automatic Reference Counting are checked (leave the other checkbox unchecked).

descr

Go ahead and click next one more time and select a location where you want to save your project.

Now that we have our project created let’s discuss a bit of what it’s going to do. Our app will allow the user to enter the text for their tweet as well as show some buttons for including an optional image and link on their tweet.

We are only going to support Portrait orientation so we need to set that up within our project settings. In your Project Navigator select the SimpleTweet project and make sure you select the SimpleTweet target inside of it, go to the Summary tab and deselect all orientations except for Portrait:

descr

Now open up MainStoryboard.storyboard and add 5 UIButtons to the view controller as follows:

descr

We have four large buttons which the user will be able to toggle in order to add an image and link to their tweet.

We’re going to make the buttons have an image from 4 different tutorials at raywenderlich.com. Drag the images from the resources for this tutorial into your project, and set up the buttons to use the images (and add some labels too) as shown below:

descr

To make this interface, simply:

  • Set the background image of the buttons to the appropriate images, and set the buttons type to Custom
  • Add 4 labels to show what each button corresponds to, and set their text color to White
  • Change the background color to a dark gray
  • Make the Tweet button’s text black

Additionally, for looks make the status bar a translucent black by adding the following line in the SimpleTweet-Info.plist file:

descr

Compile and run and make sure everything looks ok so far. Now onto the implementation!

Making Some Connections


Next we need to make some connections from our storyboard to the view controller. Open MainStoryboard.storyboard file and make sure the Assistant Editor is visible, and displaying ViewController.h.

Control-drag from each of the four labels to below the @interface, and connect them to Outlets named button1Label, button2Label, button3Label, and button4Label.

Similarly, control-drag from each of the four buttons to below the @interface, and connect them to Actions named button1Tapped, button2Tapped, button3Tapped, and button4Tapped.

Finally, control-drag from the “Tweet” button to below the @interface, and connect it to an action named tweetTapped.

When you are done, your header file should like this:


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *button1Label;
@property (weak, nonatomic) IBOutlet UILabel *button2Label;
@property (weak, nonatomic) IBOutlet UILabel *button3Label;
@property (weak, nonatomic) IBOutlet UILabel *button4Label;

- (IBAction)button1Tapped:(id)sender;
- (IBAction)button2Tapped:(id)sender;
- (IBAction)button3Tapped:(id)sender;
- (IBAction)button4Tapped:(id)sender;
- (IBAction)tweetTapped:(id)sender;

@end


Awesome! Now let’s implement these methods to send out some tweets!

In order for us to use the TWTweetComposeViewController we need to add the Twitter framework to our project. Select your project in the project navigator and then the SimpleTweet target. Go to the Build Phases tab and click on the + button inside the Link Binary With Libraries section, on the window that appears navigate to the Twitter.framework file and click Add:

descr

Next, open ViewController.m and add the following import at the top of the file:


#import <Twitter/Twitter.h>


That’s all we need in order for our file to see the Twitter API, let’s now add some code so we display the tweet sheet when the user taps the Tweet button. Go to your tweetTapped method add the following code:


- (IBAction)tweetTapped:(id)sender {
{
if ([TWTweetComposeViewController canSendTweet])
{
TWTweetComposeViewController *tweetSheet =
[[TWTweetComposeViewController alloc] init];
[tweetSheet setInitialText:
@"Tweeting from iOS 5 By Tutorials! :)"];
[self presentModalViewController:tweetSheet animated:YES];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Sorry"                                                            
message:@"You can't send a tweet right now, make sure 
your device has an internet connection and you have
at least one Twitter account setup"                                                         
delegate:self                                             
cancelButtonTitle:@"OK"                                                  
otherButtonTitles:nil];
[alertView show];
}
}


Yes, believe it or not that’s all we need to do in order to send a tweet (mind you we haven’t included any links or images), it doesn’t get any easier than this! Let’s go over the code we added to our tweetTapped method.

First thing we do is check to see if we can send a tweet, we accomplish this by calling the canSendTweet class method on TWTweetComposeViewController. This method will return NO if the device cannot access the network or if the user hasn’t setup a Twitter account yet.

If our application can send a tweet then all we do is create an instance of the TWTweetComposeViewController, use the setInitialText: method to load up the tweet sheet with some default text and present it modally. If we cannot send a tweet then we just show a simple alert view to provide the user with feedback.

Build and run your project, touch the Tweet button and this is what we get:

descr

Awesome, huh? If you get the Alert dialog, be sure you have your Twitter account set up by loading the Settings app and selecting the Twitter category.

There is one thing worth mentioning and that is that the TWTweetComposeViewController has a completion handler property which you can use to pass in your own block of code once the tweet sheet is dismissed.

By default the completion handler dismisses the modal tweet sheet, though you can customize it to do whatever you need to. Just keep in mind that if you do implement your own completion handler then you need to dismiss the tweet sheet yourself.

Adding Images and Links


Now let’s implement the logic to allow the user to select one of the tutorials and have its image and link added to the tweet. Add the following category before the implementation inside ViewController.m:


@interface ViewController ()
@property (strong, nonatomic) NSString *imageString;
@property (strong, nonatomic) NSString *urlString;
- (void)clearLabels;
@end


All we are doing here is creating two private string properties to store the image’s name and the link to the tutorial website as well as a private method to set our labels’ text color back to white.

Then add the synthesize statements for these variables:


@synthesize imageString = _imageString;
@synthesize urlString = _urlString;


And set the properties to nil inside viewDidUnload:


self.imageString = nil;
self.urlString = nil;


Next, implement the clearLabels method to set the text color of each label to white:


- (void)clearLabels
{
self.button1Label.textColor = [UIColor whiteColor];
self.button2Label.textColor = [UIColor whiteColor];
self.button3Label.textColor = [UIColor whiteColor];
self.button4Label.textColor = [UIColor whiteColor];
}


Yup, that’s all this private method will do for us.

The way we are going to implement this is as follows: when the user selects a tutorial we store its image name and link within our private properties and we set the label’s color to red in order to indicate the current selection.

If the user selects another tutorial then we just set all the labels back to white, store the new image and url and set it’s label to red. Add the following code for your button tapped methods:


- (IBAction)button1Tapped:(id)sender {

[self clearLabels];

self.imageString = @"CheatSheetButton.png";
self.urlString = @"http://www.raywenderlich.com/4872/
objective-c-cheat-sheet-and-quick-reference";

self.button1Label.textColor = [UIColor redColor];
}

- (IBAction)button2Tapped :(id)sender {

[self clearLabels];

self.imageString = @"HorizontalTablesButton.png";
self.urlString = @"http://www.raywenderlich.com/4723/
how-to-make-an-interface-with-horizontal-tables-like-the-
pulse-news-app-part-2";

self.button2Label.textColor = [UIColor redColor];
}

- (IBAction)button3Tapped:(id)sender {

[self clearLabels];

self.imageString = @"PathfindingButton.png";
self.urlString = @"http://www.raywenderlich.com/4946/
introduction-to-a-pathfinding";

self.button3Label.textColor = [UIColor redColor];
}

- (IBAction)button4Tapped:(id)sender {

[self clearLabels];

self.imageString = @"UIKitButton.png";
self.urlString = @"http://www.raywenderlich.com/4817/
how-to-integrate-cocos2d-and-uikit";

self.button4Label.textColor = [UIColor redColor];
}


In each of the methods we just clear the labels, set the image string to the appropriate image, set the URL to the corresponding tutorial and change the label’s text color to red. We could have implemented things a bit differently in order to avoid writing the same code in all 4 methods but since this example is very simple, we’ll leave it at that.

Now go over to the tweetTapped method and add the following code right before the call to [self presentModalViewController:...]:


if (self.imageString)
{
[tweetSheet addImage:[UIImage imageNamed:self.imageString]];
}

if (self.urlString)
{
[tweetSheet addURL:[NSURL URLWithString:self.urlString]];
}


We just added two if statements to check whether we have an image and url, if we do then we just add them to our tweet sheet by using the addImage: and addURL: methods respectively.

Once again, this is all we need! Go ahead and run your project; this time make sure you select one of the tutorials and hit the Tweet button. This is what we get:

descr

If you look at the tweet sheet you will notice a paper clip with 2 attachments, one is the link to our website and the other is the image we added. When the user sees the Tweet, they’ll see two URLs in the tweet – one for the image, and one for the link. Try it out and see what it looks like!

And with that my friends, we are done!

Where To Go From Here?


Here is an example project with all of the code from the above tutorial.

As you can see it’s very easy to integrate Twitter into your own applications and there is really no reason why you shouldn’t do so.

You could try and experimenting with things a bit, perhaps dynamically setting the initial text of the tweet sheet depending on what tutorial was selected, or even include more images or links within your tweet.

Have fun and think of unique ways to incorporate Twitter into your app because your users are going to love it!

If you want to do some more cool stuff with Twitter, check out our book iOS 5 By Tutorials, where we have another chapter that covers how to use the Accounts framework as well as how to access Twitter in order to acquire information such as mentions, messages, a user’s feed and more!

I hope you enjoyed this tutorial as much as I did. Feel free to post your questions and comments on the forums, I can’t wait what you guys and gals come up with for your next great app! :)



This is a blog post by iOS Tutorial Team member Felipe Laso, an independent iOS developer and aspiring game designer/programmer.

Beginning Twitter in iOS 5 Tutorial is a post from: Ray Wenderlich

没有评论:

发表评论