Subscribe ( RSS )

iPhone Programming Tutorials


 

iPhone Programming Tutorial: Integrating Twitter Into Your iPhone Applications

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

screenshot_12

If you are a developer (which you most likely are if you are reading this) you probably have (or should have) a Twitter account.  With Twitter getting so much attention lately, you would be crazy to not include some sort of Twitter integration into your own iPhone application.

There are many ways applications can be made more social by including Twitter.  For example, you could make the application auto-tweet when you unlock a special item in a game, or beat it.  This lets all of their friends know they are playing your game and in turn gets you more exposure.  You could also use this as an idea for creating your own Twitter client (don’t just submit my tutorial to the app store).

Twitter has provided us with some very simple API’s to follow making it a snap to interface with them. I have started a series on my personal blog about creating a Twitter client for the Mac that we will be borrowing some code from.

One thing I want to note before starting is: I will be going rather quick through the tutorial when it comes to creating the interface and hooking up the IBOutlets.  If you need extended help on that, this is probably not the tutorial you want to start on. Read some of my previous tutorials and come back.

This basic tutorial will just show you how to post a status update to your Twitter. I will also show you how to create an app that run entirely in landscape mode. So it’s a two-fer.

Let’s get started…

1. Create A View Based Application

screenshot_02

Name it something awesome. I called mine TwitUpdate (not awesome, I know).  The first thing we should do is create our IBOutets and IBActions. Now download the images for the tutorial and drag them into the Resources group inside of XCode.

  • btn_update
  • twit_background

screenshot_04

2. Set up your IBoutlets and IBActions

So open TwitUpdateViewController.h. And let’s add the following code:

screenshot_18

You can omit the UIButton outlets if you would like.  I just like having them around in case we want to do anything with the button.  This is pretty straight forward, we have a UITextView to enter our Twitter status in. And an IBAction that gets called to post our Twitter status.  Don’t forget to synthesize these properties in TwitUpdateViewController.m or you will be smitten by the compiler.  One other thing you will see here is a UIActionSheet.  We will display this sheet as our “Loading” screen when posting a tweet.

3. Build The Interface

Go ahead and open up TwitUpdateViewController.xib.

So if you are wondering how to get Interface Builder in landscape mode, it’s actually quite simple.  It is not obvious however as it took me forever and a freakin day to figure it out.  There is a little arrow (as in the screenshot below) in the top right corner of the view.  Click it and the view will rotate to landscape mode.

screenshot_15

Now that your interface is in landscape mode, remove the Status Bar.  This is done by clicking on the view and setting the Status Bar drop down in the attributes inspector to none. This will just give you more screen real estate.

Now drag a UIImageView on your view and stretch it to fill the entire screen.  Set the Image attribute of the UIImageView to be twit_background.png and bask in the glory of my beautifully created interface!  Next, we need to add the UITextView.

Grab a UITextView and drag in on to the view and stretch it to fit just inside of the chat bubble.  Make sure to delete the lorem ipsum text inside.

The last interface element we need to add is the update button.  Drag a UIButton on to your view.  In the button’s attributes, set it’s type to custom and it’s image to btn_update.png. Make sure you drag the button to fit the update image. Your final interface should look like this

screenshot_11

Now, connect the twitterMessageText from File’s Owner to the UITextView and the updateButton to your custom button.  Also, be sure to connect the TouchUpInside method of the UIButton to the postTweet IBAction.  Here is a screenshot of what the connection properties should look like when you click on File’s owner.

screenshot_08

Now close Interface Builder.

4. Creating Our Twitter Request Class

So, we will interface with Twitter using an NSMutableURL request and NSURLConnection.  You have two options at this juncture, you can either download the files below and add them to your project to use, or you can head on over to http://brandontreb.com/objective-c-programming-tutorial-creating-a-twitter-client-part-1/ and learn how to create them yourself (recommended route).  I would explain it here, it’s just that I already wrote an in depth tutorial for it on my blog. This is now a tutorial scavenger hunt.

3.1 Note: As pointed out, by teresa and Ivan in the comments , to get it working in 3.1

just comment out the [newCredential release] in

In – (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

We were releasing this object too early and it was causing a crash

If you just want to complete this tutorial and move on, download the file above, unzip and drag the files into your project.  We need to add some code to these files in order to post a status update to Twitter.  So, open TwitterRequest.h and update the following code

screenshot_16

We have added a Boolean that denotes whether or not we are making a HTTP POST request (Twitter uses both POST and GET).  Also, there is a string that will represent the POST request.  In our case, this will just get set to “status=foo” (foo being your status update).

Also, we have added a method signature to update your status.  It takes an NSString which is just the status text.  The other variables are explained in my tutorial on brandontreb.com.  Now, open up TwitterRequest.m and add the following code.

screenshot_17

Ok, beginning with the status_update method.  This method looks very similar to our friends_timeline method with a few exceptions.  First, we set isPost = YES.  Next, we set the request body = “status=%@” where we set %@ to our status update.

Now, for some trickier code.  In the request method of our class, we need to add some code to do an HTTP POST (rather than a GET).  This is how we tell Twitter what to set our status to.  So, the first thing is to set the HTTPMethod for the request to POST.  Next, we have set the “Content-Type” field to let Twitter know what kind of data we are sending.  Following that, the body of the request is sent.  This is the actual data that Twitter will see.  Finally, we just tell the request how large (in bytes) our data is going to be.  If this is all foreign to you, I recommend you go read up on POST and GET.

Phew… Done with that.  Now for the final part of implementing our postTweet method.

5. PostTweet Method

Open up TwitterUpdateViewController.m and add the following code.

screenshot_20

Ok, not super complex as the TwitterRequest class does most of the heavy lifting.  As a reminder, the postTweet method gets called when you press the Update button.  The first thing we do here is build a new TwitterRequest object and set the username and password field.  Make sure you put in YOUR twitter username and password.  Next, we call the resignFirstResponder method on the UITextView.  This is to hide the keyboard.

Just so the user knows something is happening, we display a simple action sheet that has no buttons and says “Posting to Twitter…” . Finally, we call the statuses_update method in our TwitterRequest class.

The Twitter request class will then do some magic and eventually call the callback method that you specified (status_updateCallback) and send it the data that Twitter returned to us.  The first thing we do is dismiss the action sheet. Next, I am simply outputting the response from Twitter in to the terminal.

The response received from Twitter would need to be parsed and displayed or something but that’s for another tutorial.One thing to note, if you enter an invalid username or password, this app will just hang and say  “Posting to Twitter” forever.  You need to handle this in an error callback method. Again described in the tutorial in which we took the TwitterRequest code from.

6. Run The App In Landscape Mode

The last part of this tutorial is to force the app to run in landscape mode as well as hide the status bar.  Open up TwitUpdate-Info.plist. Right click on the table and select “Add Row”. Select Initial interface orientation and set the value to Landscape (left or right).  Right click again and add Status bar is initially hidden. to hide the status bar.  It should now look like this.

screenshot_21We also need to update the TwitUpdateViewConroller.m file to respond to the interface rotations.  Uncomment the following method in TwitUpdateViewController.m and change it to say:

screenshot_22

Just tells the the view to rotate when the iphone is rotated…

Well, I hope you have enjoyed this tutorial.  I hope to see some cool Twitter integration in all of your apps (feel free to comment and let me know how you have implemented it in your app).  You can always ask questions in the comments of the post or write me on twitter.  And for lazy people here is the source (j/k).  Happy iCoding.

 

52 Responses

AppStoreMod Says:

July 9th, 2009 at 1:40 pm

Great Tutorial. Can you guys make a tutorial on how to make a twitter have customized background to each update. That would be awesome.

Picoman Says:

July 9th, 2009 at 2:50 pm

Another great tutorial, I thank you!
I can only spend an hour a day learning at the moment (until i lose my job on 31st July…) and you really help make the learning process fast and straightforward. Hopefully going to submit my first app in the second week of August. This site is a great resource. If you need any help with anything, just ask.

danno Says:

July 10th, 2009 at 9:10 pm

looking back on some of your other posts, all of the source code and screencast links are broken. might wanna take a look at that.

rockteady,
danno~

Gaurang Says:

July 13th, 2009 at 9:19 am

Hello

I am facing problem with invalid username and password ,it stucks with the UI actionsheet even if the username or password is incorrect .

Also it doesnot leave out in case of no network connection .

Please help me out I am facing this problem from 3 days .

I require only post method so this is the great tutorial for me thanks

mail me on gtechonly4u@gmail.com

Techy Says:

July 14th, 2009 at 8:23 am

I could not get mine to work correctly so I downloaded your example, ran it and got the following error:

CodeSign error: Code Signing Identity ‘iPhone Developer’ does not match any code-signing certificate in your keychain. Once added to the keychain, touch a file or clean the project to continue.

Do you know how I can fix this??

Brandon Says:

July 14th, 2009 at 9:55 am

@Techy,

You need to build for the simulator. You are getting this error because you are building for the device and don’t have the signing set up.

Techy Says:

July 14th, 2009 at 11:33 am

how do i make is build for the simulator??

LiveCity Says:

July 14th, 2009 at 11:58 am

I have a rather lengthy question to ask you. Where/how do I do that?

Thanks,
D

Brandon Says:

July 14th, 2009 at 3:40 pm

@Techy

Click the dropdown on the top left corner of XCode (right now it should say something like “Device 2.2.1 | Debug”, click that and change to iPhone Simulator 2.2.1

@liveCity

http://brandontreb.com/contact-me

Techy Says:

July 14th, 2009 at 4:58 pm

Thanks for all the help, after about 7 computer restarts and fixing that error it worked lol.. I have one last question, when you buy standard certificate or whatever that allows you to post on the app store, do you get lessons on how to program with the iphone sdk??

Apple iPhone Appstore Application Analytics - Mobclix Says:

July 15th, 2009 at 4:35 am

Thanks for sharing this all, it’s really useful for us,

Jeremy Says:

July 18th, 2009 at 1:08 pm

when i try to run it it just stays frozen at the posting to twitter action sheet. no prompt for username or password or anything. anybody know how to fix this?

Techy Says:

July 18th, 2009 at 9:04 pm

@Jeremy

You put your username/password into the code, look under section five: postTweet method, of this tutorial..

Good Luck!

Mayank Says:

July 20th, 2009 at 4:12 pm

Without a doubt a great tutorial
how can i integrate it with an app of mine
like if i want to add it to my app so that the user can key in his username and password and then send tweets etc
this wil work only for me i guess

thanks

Jeremy Says:

July 20th, 2009 at 11:37 pm

@Mayank

yeahh thats the kind of idea I was trying to get at. But i guess this only works for one person whos a dev??

Brandon Says:

July 21st, 2009 at 2:31 pm

@Mayank @Jeremy

It’s not hard at all. Just read through some of my other tutorials about creating new views, etc… and add another view in front of this one that prompts for a Twitter username and password.

Then, once the user enters these credentials save them with NSUserDefaults (again read my tutorial on this)

Jason Says:

July 22nd, 2009 at 10:24 pm

I am using the iPhone beta 3.1 beta 2 and when I click on the update button I get a error saying unable to read unknown load command 0×22 and I have no idea what that means. It works perfectly fine in simulator 3.0.

Can anyone help?

iPhone Programming Tutorial: Animating A Game Sprite | iCodeBlog Says:

July 24th, 2009 at 11:52 am

[...] Double click on whateveryoucalledyourapplicationViewController.xib to open it in Interface Builder. Click the arrow button on the view to rotate it. If you don’t what I am talking about, check out this post. [...]

Mike Says:

July 25th, 2009 at 7:05 am

I tried adding a new field to info.plist and the Initial interface orientation and Status bar is initially hidden options are not available from the dropdown. Any ideas/thoughts/suggestions.

Thanks in advance!

Mike

Caleb Says:

July 26th, 2009 at 1:27 am

Thanks for the tutorial. I am struggling to get the text to reset after being sent to Twitter. How would one go about this?

Brandon Says:

July 26th, 2009 at 9:55 am

@Mike – You have to manually type them. They are not in the default set.

@Caleb – Just do twitterMessageText.text = @”"; in the postTweet method

Ivan Says:

July 26th, 2009 at 11:00 am

Tried it on 3.0 and it works. On 3.1 Beta 2 it crashes when posting. Hope you can update the tutorial later on for 3.1. betas :)

Brandon Says:

July 27th, 2009 at 11:08 am

@Ivan, What’s the error for the crash?

Geoff H Says:

July 27th, 2009 at 10:14 pm

Awesome tutorial, thanks much. I do have one question though – what about encoding the message to tweet? Certain characters cause problems – for example, entering “&” causes it and everything after to be cutoff. So far I cannot find the encoding members I’m looking for.

Jason Says:

July 28th, 2009 at 6:51 pm

I am trying to validate the username and password on a settings page i have and wanted to know the correct API call. I am using http://twitter.com/account/verify_credentials.xml but I don’t know the parameters it needs please help me.

Jason Says:

July 31st, 2009 at 10:34 pm

@Brandon or @Ivan and luck with the 3.1 Beta 2 crashes???

Ivan Says:

August 8th, 2009 at 1:07 pm

Jason: “Unable to disassemble objc_msgSend.”

On beta3 simulator and on device.

Ivan Says:

August 8th, 2009 at 1:08 pm

and “EXC_BAD_ACCESS”

Shabbir Says:

August 9th, 2009 at 12:07 pm

I am having the same problem as Ivan. I get EXC_BAD_ACCESS
I really hope this is just a problem with Apple, because I have an app in the app store using this code and it will not work on 3.1

brandon Says:

August 9th, 2009 at 1:13 pm

I’ll check this out this week and post the fix. Sorry about that, Apple must have changed something in 3.1

Ivan Says:

August 9th, 2009 at 2:09 pm

thanks brandon. really appreciate it. like Shabbir, I have an app which will be out in time for 3.1 and would like to be able to get this working by then. :)

let me know if you need help troubleshooting on 3.1 (you have my email me thinks)

Jason Says:

August 9th, 2009 at 7:00 pm

Thanks @brandon I can’t wait.

iPhone Programming Tutorial: Integrating Twitter Into Your iPhone … | IPhoneMate Says:

August 12th, 2009 at 9:31 am

[...] See the rest here: iPhone Programming Tutorial: Integrating Twitter Into Your iPhone … [...]

Qi Says:

August 13th, 2009 at 2:18 am

Great code, thanks!
I’m quite happy to find it.

Ivan Says:

August 16th, 2009 at 6:43 am

Any news on this for 3.1 brandon? :)

teresa Says:

August 18th, 2009 at 9:20 am

@Ivan
In – (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

The exec_bad_access was in fact because [newCredential release]; was in the code, but the newCredential wasn’t being retained before.

I don’t know it didn’t happen on the original application, but when I copied the code to another application it happened and I had to debug the code using instruments.

Great tutorials!
thanks

Ivan Says:

August 19th, 2009 at 3:35 pm

@teresa

Just tested and it works. :) Thanks for that.

Shabbir and Jason, just comment out the [newCredential release] in

In – (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

Julian Says:

August 20th, 2009 at 12:59 pm

Great Tutorial, thanks!
I needed it this feature for my app and now it works fine!

Julian

Jason Says:

August 23rd, 2009 at 11:29 am

Ivan thank you so much it is finally working hooray!!!

Jason Says:

August 23rd, 2009 at 11:29 am

Does anyone know how to pull down the profile picture?

antony Says:

August 25th, 2009 at 11:57 pm

Hi it is rally an excellent tutorial. it works for me. I am really thank full to you. I would like to know that is there any way to change the footer of the status message from “from the api” to “from my application”

iPhone Programming Tutorial: Animating A Game Sprite | Iphone Study Blog Says:

September 4th, 2009 at 6:03 pm

[...] Double click on whateveryoucalledyourapplicationViewController.xib to open it in Interface Builder. Click the arrow button on the view to rotate it. If you don’t what I am talking about, check out this post. [...]

Mustafa Says:

September 8th, 2009 at 9:29 pm

Very nice post. Thanks for sharing. I would love to see a similar post for publishing information on Facebook!

Ram Says:

October 7th, 2009 at 8:01 pm

Has anyone found the fix for the problem where if the character “&” is used in the text, the message is truncated?

superbgx Says:

October 12th, 2009 at 2:47 am

Hi, great tutorial ! thanks for sharing with us.
If the user and pass don’t match the loading action sheet won’t close and you have to restart the app.You’ll need to add this before the NSLog(@”Invalid Username or Password”); line

UIAlertView *myAlert = [ [ UIAlertView alloc ]initWithTitle:@”twitter” message:@”Invalid Username or Password” delegate:self cancelButtonTitle: nil otherButtonTitles: @”OK”, nil];
[myAlert show];
[myAlert release];
[delegate performSelector:self.callback withObject:receivedData];
NSLog(@”Invalid Username or Password”);

Brandon Says:

October 12th, 2009 at 1:41 pm

I have updated the TwitterReqest class to include the fix for 3.x. It should no longer crash :)

Ram Says:

October 12th, 2009 at 8:17 pm

@Brandon, could you also check the problem where if the text contains the character “&”, then the message gets truncated?

Brandon Says:

October 13th, 2009 at 9:16 am

@Ram that is bc the text needs to be url encoded. I’ll add that to the tutorial.

Andrea Says:

October 13th, 2009 at 8:31 pm

I have a problem, please help me!

error: Cocoa/Cocoa.h: No such file or directory

when I remove #import from TwitterRequest.h then it says

“_NSlog”, referenced from:
-[PruebaViewController status_updateCallback:] in PruebaViewController.o
symbol(s) not found
collect2: ld returned 1 exit status

I don’t now what I’m doing wrong, I’ve done exactly what the tutorial said

Ram Says:

October 14th, 2009 at 9:12 pm

@Brandon – thx, i tried using [NSString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding] but it didn’t work. Maybe there’s another way to do it

kewl Says:

October 22nd, 2009 at 5:18 am

@Brandon

first of all thank you for posting twitter integration code to Iphone. It’s really helpful

I have just got a very quick question.

in addition to your code, I have created

- (void) isPostSuccess code which return the value of isSuccess.

What i’m trying to do is checking if the user name and password entered was correct. So I set isSuccess = NO in the below code

However, I’m having issue on finding where should I set isSuccess = YES ?

Your advise is greatly appreciated.

thank you

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
//NSLog(@”challenged %@”,[challenge proposedCredential] );

if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential=[NSURLCredential credentialWithUser:[self username]
password:[self password]
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential
forAuthenticationChallenge:challenge];

//[newCredential release];
} else {
isSuccess = NO;
[[challenge sender] cancelAuthenticationChallenge:challenge];
[delegate performSelector:self.callback withObject:receivedData];

NSLog(@”Invalid Username or Password”);

}

}

Narender Says:

October 24th, 2009 at 6:52 am

Hi Brandon,
I saw one application around me, there first it is checking usrename and password and if it is okey than it allows user to enter text. how to do that ? here we are writing the text first and attempting it so post. so we have to pass the message than it will ask for username and password. can you please post something like asking username and password than checks the credentials, if correct than asks for message ?????

Leave a Reply