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
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.
2. Set up your IBoutlets and IBActions
So open TwitUpdateViewController.h. And let’s add the following code:
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.
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
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.
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
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.
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.
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.
We 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:
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.














96 Comments
@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”);
}
}
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 ?????
Im gettitng this error
2009-11-17 15:44:51.379 TweetApp[3212:20b] ispost
Current language: auto; currently objective-c
2009-11-17 15:44:53.443 TweetApp[3212:20b] Connection failed! Error – Operation could not be completed. (NSURLErrorDomain error -1012.) http://twitter.com/statuses/update.xml
2009-11-17 15:44:53.444 TweetApp[3212:20b] Invalid Username or Password
I already my correct user name and password.
Any Idea is greatly appreciated.
i have this in the posttweet method:
TwitterRequest * t = [[TwitterRequest alloc] init];
t.username = [NSString stringWithFormat:@"%@", [usernamePlace text]];
t.password = [NSString stringWithFormat:@"%@", [passwordPlace text]];
[usernamePlace resignFirstResponder];
[passwordPlace resignFirstResponder];
loadingActionSheet = [[UIActionSheet alloc] initWithTitle:@”Posting To Twitter…” delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
[loadingActionSheet showInView:self.view];
NSString *myTweet = [[NSString alloc] initWithFormat:@”I took %i second/s to complete a level on the #DodgeIt! iPhone Game. Try and beat that! Get it on the App Store: http://bit.ly/6QnAhP“, mainInt];
[t statuses_update:myTweet delegate:self requestSelector:@selector(status_updateCallback:)];
[myTweet release];
so the user puts in their twitter info and then is posts a tweet already put into the app but when i hit the post button it shows the actionsheet but thwn it crashes.
anyone know how to solve this?
How do I set it up for me to have a label for username and password in IB instead of having to type it in the code
Sorry about a late reply, but if you still need help you could, have a front screen with two text boxes and you type in your details and when you click log in it stores your details into labels, and then instead of t.username=@”example@ it could be t.username=label.text etc but the front screen wont check if the twitter details are correct but I hope this helps.
hi, can i ask you something about chat. Can i use image emoticon for some special character like
? So, i can change every “:)” with smile icon… can you help me, please.
@Tommy Myers
I am Completely NEW to iphone integrating with Twitter
Thanks for the wonderful post.and also thanks to other people who have given their views.Mr.Tommy Myers I also need the same thing that you want.And I have also tried your code that u have post in this.And even I am facing the same thingDid you got the solution to this if yes please give to me also.
@Tommy Myers
Can You give me your complete code.
Thanks in advance.If possible for you mail me.
mail me at:hardikpatel1987.007@gmail.com
@Tommy Myers
Hey Tommy, I am facing the exact same issue that you are. Have you been able to find anything on this issue. My application crashes as well. Not sure what is going on.
Please help me out. Thank you so much. You can either post here or my email address is tech@kdp-tech.com
Thanks again,
Keyur Patel
The & problem
This is suppose to work:
NSString* escapedUrlString =
[unescapedString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
But doesnt… I think its an apple bug
This works everytime for all special characters!
MyTweetMsg = (NSMutableString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)TempMessage,NULL,(CFStringRef)@”!*’();:@&=+$,/?%#[]“,kCFStringEncodingUTF8);
Hi, can we send/post images also using this code? What changes will be required? Any idea? (Sorry for being dumb on this)
@Brandon
I want to create a full on Twitter client for the iPhone, so
1.Where did you learn this?
2.Where should I get started?
Hi thanks a lot for a perceptive post, I actually found your blog by mistake while looking on Goole for something else closely related, anyhow before i ramble on too much i would just like to state how much I enjoyed your post, I have bookmarked your site and also taken your RSS feed, Once Again thanks for the blog post keep up the good work.
Thanks for this awesome tutorial, it’s helped me out a ton! One thing that I’m trying to figure out though is how to use the other API’s, especially the GET kind. Your post says if I don’t understand it, I should read up on POST and GET. Do you have any recommendations?
Thanks.
hi Brandon, I am testing the twitter tutorial and it works like a charm. it only seems to update my test message only once, although I always seem to get into the callback without errors.. When I check at the site it never adds the same msg 2 times, when I change the message every time it works perfect..
Am I missing something?
@Thomas – Twitter doesn’t allow duplicate posts. This is why you must change the message for it to work.
Thanks for reading!
Thanks for writing it.. Coming from a strong Flash Lite background it’s not always easy to step into objective-c. I like your tutorials because they are also very syntax-driven. I understand most code/programming concepts, but the syntax is so new
Any way, i’m very happy with you sharing your knowlegde!
Greets from belgium
Thax a lot guys.. great tutorial and comments discussion.
@teresa Thx a lot as well ur comment was a life saver..
Hi guys!
I implemented a postTweet method to my app, of course with some customizations. During checking for leaks I find 3 leaks. I add a following code to dealloc method of TwitterRequest.m:
-(void) dealloc {
//added code
[username release];
[password release];
//
[super dealloc];
}
And in ViewController.m I pass a declaration of tRequest
to interface, it is allow me to release this object after posting.
@interface ModalTweetController … {
TwitterRequest *tRequest;
}
In status_updateCallback method I release it
- (void)status_updateCallback:(NSData *)content {
…..
[tRequest release];
}
Leaks free app is a lucky app!!!
My partner and I harmonise together with your results and can anxiously look ahead for your future revisions. Just declaring thanks will never just be enough, for that outstanding quality inside your writing. I’ll instantly grab your rss feed to stay up-to-date of any messages. Great work and much results with your online business endeavors! Toodles!
We agree along with your results and may hungrily look ahead on your future revisions. Only expressing many thanks won’t simply be enough, for that exceptional readability in your writing. I am going to immediately seize your rss to keep up-to-date with all updates. Solid effort and much achievement with your internet business endeavors! Whatwhat!
hello
i am using this code in xcode 3.1.3 and i was getting EXC_BAD_ACCESS error. i have solved this by renaming username and password variable to tusername and tpassword.
hope this will help someone
BTW nice tutorial.
hello
This is nice application
Now i want show all tweets which are reside in my account on my iphone
for this reason i parse the reply come from twitter account
but it shows only the information about what i am posted
i also tied other twitter api url (s).
Please tell me what i do.
Thank you very very much!
I just need this tutorial.
Having EXE_BADACCESS, according to Console:
2010-04-05 10:21:34.292 TwitUpdate[158:207] ispost
Program received signal: “EXC_BAD_ACCESS”.
Help!
In – (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@”DelegateretainCount: %d”, [delegate retainCount]);
}
each time if you click on update button delegate retain count will increase and it will never come down.
Normally we dont retain the delegates so if you assign delegate retain count remains 2.
@property(nonatomic, assign) id delegate;
HEy how do I add the the updateButton to your custom button.Can u help me plz ASAP
Thanks
If you are getting EXC_BAD_ACCESS from the NSAutoReleasePool
try removing [newCredential release] since it is freed by the AutoReleasePool
Thanks
Hi!
Im trying to put a simple twitter search option (so no sign-in) in my iphone
application, but dont understand how to do so. All
the resources seem to be for posting things…. Can somebody
please help? Thanks!
This needs to be updated for OAuth.
wow, this post is G – R – E – A – T,
or maybe just great.
I am completely new to iPhone coding (literally, I am only 11),
but this was so easy to follow!
nice tutorial, but I don’t bring it to work on 3.2 or 4.0 (it works just sometimes – but this isn’t reproducealbe). The most time the app quits and sometimes I get a log, sometimes not. If there is a log, it says: TwitUpdate(3573,0xa0bef4e0) malloc: *** error for object 0xb203210: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
I couldn’t figure out what’s going wrong…
Ok, FORGET about my last post, I just didn’t see the solution of this problem on the previous comment-site!
Thank for this super tutorial !
How did you fix this? Where did you look to find the fix?? Thanks -Bob -
I think the code is missing something.
Here i got the error :
/Users/birkoff/Documents/TwitterUpdate/Classes/TwitterUpdateViewController.m:25:0 /Users/birkoff/Documents/TwitterUpdate/Classes/TwitterUpdateViewController.m:25: warning: incompatible Objective-C types ‘struct UITextView *’, expected ‘struct NSString *’ when passing argument 1 of ‘statuses_update:delegate:requestSelector:’ from distinct Objective-C type
And here’s the line :
[t statuses_update:twitterMessageText delegate:self requestSelector:@selector(status_updateCallback:MISSING_SOMETHING HERE)];
Anyone can help?
I’m sorry, my bad. I fixed it.
I have soved the credentials…
Hi Brandon, fantastic tutorial. I heard that twitter will not support their api’s with basic auth starting June 30th. Will your app still work? Or do you have some new codes with XAuth recommended by twitter.
Great tutorial
It all works, apart from dismissing the keyboard?
Clicking update dismisses the KB, but a lot of people will click return after typing their tweet, and alas nothing happens. Is there any code to plumb in to dismiss the KB after hitting return?
My app gets stuck on the screen where the action sheet pops up.. The logs say that there is no response from the delegate. Testing currently on 3.2 and 4.0
Thank you for your great tutorial but i have a problem , iam using this api on my iPad application but when user tap on UPDATE button my app going to crash and debugger detects EXC_BAD_ACCESS , i think this api doesn’t work on SDK 4 !
i really need this client , even i downloaded you source code but i had same problem !
what’s the solution ???
i read all comments and solve the problem
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 ?????
It’s not working in ios 4.
it just crash……..
I found the solution…
in the method
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
}
remove this code:
[newCredential release];
whoompppppppppp
11 Trackbacks
[...] 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. [...]
[...] See the rest here: iPhone Programming Tutorial: Integrating Twitter Into Your iPhone … [...]
[...] 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. [...]
[...] July of last year. Brandon put up a post showing you how to integrate twitter into your application. Today I am going to take the class he [...]
[...] Tutorials helfen bei alltäglichen Problemen weiter, so finden sich darunter eine Anleitung um Twitter in eine iPhone-Applikation zu integrieren oder um Push Notifications zu nutzen. Weiterhin finden [...]
[...] Integrate Twitter into your app – Utilise the Twitter API to integrate Twitter into your iPhone app. [...]
[...] Tutorials helfen bei alltäglichen Problemen weiter, so finden sich darunter eine Anleitung um Twitter in eine iPhone-Applikation zu integrieren oder um Push Notifications zu nutzen. Weiterhin finden [...]
[...] July of last year. Brandon put up a post showing you how to integrate twitter into your application. Today I am going to take the class he [...]
[...] Integrating Twitter Into Your iPhone Applications [...]
[...] July of last year. Brandon put up a post showing you how to integrate twitter into your application. Today I am going to take the class he [...]
[...] Integrating Twitter Into Your iPhone Applications. Con questo tutorial approfondiamo l’uso delle API realizzando un lettore di feed twitter completo. [...]