So with all of the buzz and hoopla about Twitter lately, I thought I would start a tutorial series demonstrating how to create a simple Twitter client for the Mac. I will be showing you how to use Objective-C to connect to Twitter, login, get and post tweets.
In the first part of this series, we will simply be getting connected to Twitter and displaying our public feed in the debug terminal.
So let’s go ahead and get started… First make sure you head on over to developer.apple.com/mac and scoop up the latest version of the SDK. If you have already installed the SDK for iPhone development, you should be fine.
Create A New Project
Go ahead and open up XCode. Click File -> New Project… Under the Mac OSX heading, select Cocoa Application. This will create a few base files to start our applicaton. Make sure you name it something awesome; preferably include “tw” somewhere in there or relate it to birds. I’m going to name mine Chirpie. That sounds pretty Twittery.
So the first thing we need to do is develop a class that will make a connection to Twitter.
Create Our TwitterRequest Class
The TwitterRequest class will be the meat of our Twitter application. It will contain all of the code to connect to Twitter as well as all of the Twitter API functions. So bear with me and feel free to ask questions about any part of this tutorial.
To add a new file to your project, click File -> New File and select Cocoa -> Objective-C class
Name this file TwitterRequest and make sure the box that says “Also create TwitterRequest.h” is checked. Click Finish.
Open up TwitterRequest.h and add the following code. I’ll explain what it does below…
So before you leave me angry comments about putting up an image rather than the source text, let me explain. I have gone through many programming tutorials, and have found that I learn far less by copy and pasting than by typing all of the code myself. If you really don’t feel like typing the code yourself, you can always download the source at the bottom of this post.
Ok, so the first 2 variables here are just username and password. Whenever you make an API request to Twitter, they will prompt you for a username and password. You will see in TwitterRequest.m how we will send this to them.
Next, we see receivedData. This is just a buffer for holding the XML that Twitter sends back to us. As Twitter sends us data, we will append it to this variable.
The final 3 variables all have to do with handling the data once we are finished communicating with Twitter. Let’s first talk about the callback variable. This is the function that our TwitterRequest class will call once it receives the data from Twitter. It will pass the received data to that function. The delegate variable simply tells our class where this function is. Finally, we have an errorCallback variable. This is a method (inside of the delegate) that gets called if there is an error receiving data.
Next, we define 2 methods. The first, is named after the Twitter API call friends_timeline. And does just that, returns the friends timeline. The next is a helper method that does all of the heavy lifting. All of the Twitter API methods we implement will call the request method.
One thing to note is the method signature of friends_timeline. It takes a delegate and a selector. This is just telling our Twitter class to send the data to a given method within a given object. Now, let’s implement this class. Open up TwitterRequest.m and add the following code:
This will create the “getter” and “setter” methods for our variables. Make sure you add them after the line @implementation TwitterRequest. Next, we implement our friends_timeline method. Add the following code:
As you can see, this method is quite simple. It will be used by all of our Twitter API methods. This is because we pass off all of the hard work to the request method. The friends_timeline method does a few things. First, it sets the delegate and callback properties for the class. Then, it calls the request method with a given URL. You can find all of Twitter’s API calls here.
Now, for the fun part… Let’s implement the request method. Add the following code:
Ok, so not too much to this method. First, it creates an NSMutableURLRequest from our URL and passes that to an NSURLConnection. If we were able to connect (theConnection is not nil), we instanciate the receivedData property. Now, an NSURLConnection has some delegate methods that we need to implement in order to receive and manipulate the data. The first one in our case being the connection didRecieveAuthenticationChallenge method.
This method gets called when the web service you are trying to access requests a username and password. So in this method, we simply give it our Twitter username and password. Add the following code:
First, we check the previousFailureCount variable to see if this is the first time we have been asked for a username and password (if not, you know your current credentials are incorrect). Next, we build an NSURLCredential using our Twitter username and password. And the magic of the objective-c libraries handles the rest.
The next method we need to implement gets called when we receive a response from the server. We just use this as an opportunity to clear out the received data. Add the following code:
Pretty simple… Stay with me, we have 3 more delegate methods to implement. Add the following code:
I love the simplicity of this method. It gets called evertime we receive bytes of data from the server. Once data is received, it can be appended to the receivedData property. (No malloc needed!). This next method is optional if you want to be lazy, but needed if you want your Twitter program to be robust. So just add it…
The didFailWithError method gets called when there is a problem communicating with the server. This is important in our application as Twitter seems to have periodic issues when they become overloaded. We’re in the home stretch… The last method for this class is the connectionDidFinishLoading method. Add the following code:
This gets called after we have received our response from Twitter. Notice the line:
[delegate performSelector:self.callback withObject:receivedData];
That calls the method we will specify and sends the receivedData to it to be processed. Finally, we release our request variables to be nice to the users’ memory.
Using The TwitterRequest Class
Ok, so we have laid the ground work for our TwitterRequest class. Now I will show you how to use it to easily interface with Twitter. We will need to create one more file that will act as the delegate for our application. So, once more click File -> New File… and select Objective-C class. Name this file ApplicationDelegate and be sure to check the box that says “Also create ApplicationDelegate.h”.
We need to tell our application that this class will be its delegate. The way to do this is through Interface Builder. So, double click on the file MainMenu.xib to open it in InterfaceBuilder.
See the video below on how to create the connection.
[QUICKTIME http://brandontreb.com/wp-content/uploads/2009/06/IBSetup.mov 634 396 false true]
Now that our Connection has been made, we need to simply construct a TwitterRequest object and call the friends_timeline method when our application starts. Go ahead and open ApplicationDelegate.h and add the following code:
We are just declaring the callback method that will be called by our TwitterRequest class. Notice that it takes an NSData argument. This will be the data returned by Twitter. Now open ApplicationDelegate.m and add the following code:
So the first thing to see here is we are overriding the applicationDidFinishLaunching method. This is the method that gets called when the application starts. So we create a new instance of the TwitterRequest class and set the username and password fields. Next, we simply call the friends_timeline method on the class, passing it self as the delegate and friends_timeline_callback as the callback.
Once our request has been processed and Twitter returns some data to us, the friends_timeline_callback method will get called with the data. So we convert this data to a string and print it out.
And there you have it, we have successfully connected to Twitter and displayed our friend timeline. Next week I will be showing you how to parse this response and get it into a format that we can use in our applications. If you have any comments or questions, feel free to leave them below. You can also download the source for this tutorial below.
Twitter Mac Client Tutorial 1 – Source
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!
Tags: cocoa, iphone twitter, mac coding, nsurlcredential example, Objective-C Twitter, Programming, twitter api iphone
















This is pretty solid. Looking forward to the next one.
Very nice! Thanks
Superb, just what i was looking for to a) understand Objective C a bit more and b) understand the twitter API – great work, keep it coming
This is exactly what I am looking for! I am writing an iPhone app that will use the Twitter API. Good stuff Brandon! kthx
What Austin said above – I really enjoyed this – and I can’t wait for next version on how to parse and display the tweets! I’m looking to make a iPhone application for Twitter.
Thanks for the information!
hi brandon
thank you very much for your working NSURLCredentials example!
looked into a ton of pages, but your very clean and straight-forward example was very informative. i’ve been able to implement my NSURL-stuff as i wanted now.
and yes, as macJasp told: i also learned a lot about objective-c with your walkthrough; didn’t know that delegate-thing till today.
thanks again & best wishes from switzerland,
manuel
thanks for supporting novice programmers like me. This tutorial helped alot. Thanks from Japan.
Hi Brandon,
This is an awesome tutorial. I have been searching high and low for something like this on google. Thanks a lot man!
In applicationDidFinishLaunching “tr” is allocated but never released. Wouldn’t this cause a memory leak? Also friends_timeline_callback allocates “timeline” but doesn’t release it.
It would, I would suggest doing a [tr release]. I’ll update this post when I put up part 2.
Very clean code! Nice.
How hard would this be to get working on the iPhone sdk. For example, I don’t think that NSURLAuthenticationChallenge is available in the SDK…
I answered my own question. It works great with the iPhone SDK.
Just noticed that you define theRequest as an NSURLRequest, but you are initializing it as an NSMutableURLRequest. I think these should be consistent one way or the other. I personally prefer NSMutableURLRequest.
This is a great tutorial… it’s very clear (and thanks for not making the code copy/paste-able, it really helps!)
Can’t wait for part two.
–Brad
great tutorial!
Verry nice!
Is it good practice to return the request object along with the data to be able to release the request in the callback? like so:
in TwitterRequest.m:
[delegate performSelector:self.callback withObject:recievedData withObject:self];
in delegate:
- (void) friends_timeline_callback:(NSData *)data fromRequest:(TwitterRequest *)request{
/*do stuff*/
[request release];
}
Actually, you can go ahead and release the request right after you are done calling the [tr friends_timeline]. So just do, [tr release] on the next line.
I was just lazy. Good catch though!
I’m getting a blank window when I run this. It happens even when I download the Chripie app. What do you think I’m doing wrong?
Hey Mike,
You should get a blank window as we have not created the interface yet. I am almost done with the next part of the tutorial so we will start seeing some stuff.
However, if you open up the console, you will see the XML returned from Twitter. That is what this tutorial is all about.
To open the console in XCode:
Click Run -> Console
In the next tutorial, I will discuss how to parse this response from Twitter and begin creating the interface.
Thanks for reading.
Ah! Thanks.
It was driving me crazy.
Brandon,
Do you know how to adapt this code to hit the Tweetworks api? http://www.tweetworks.com/pages/api
I’m lost on how to use the API key.
Full disclosure, I’m the founder of Tweetworks. I’m not a developer (I hired the firm that built the site, but they aren’t iPhone developers.) I’m trying to tinker around with the things myself for fun but getting stuck.
Yea, it doesn’t look like it will be too hard. Your API requires POST and we haven’t implemented yet. I’ll have the next tutorial in this series up sometime this week which should detail that.
If you are really daring, you can check out my iPhone tutorial that I wrote here which does include POST.
Cool. How about the API Key piece? The Twitter API doesn’t require a key, but Tweetworks does. That’s mainly to slow down potentially malicious apps and have some understanding where volume comes from.
If you’d prefer to take this convo off your blog, please feel free to email me. That is if you are feeling generous with your time.
I don’t mind it on my blog. Prob more efficient for me than email. The API key will just get sent in the POST. It looks like your POST should look like data[key]=keyval&data[Post][body]=posttext&data[Post][sendToTwitter]=1.
If you read the other tutorial I pointed you to, it should become apparent where this should go.
Excellent. I’ll rock through the other tutorial.
I sincerely appreciate the help. I can’t tell you how maddening it is to not know how to work on my own product.
Users are clamoring for a Tweetworks powered iPhone app but as a self funded startup things take time.
Very nice tutorial, learn a lot. I’ll bookmark it and looking forward to part 2.
Great tutorial, Brandon. Have you considered writing one with OAuth.
HI,
I am getting this line “less than 20 seconds ago from Api” after the status..
I want my site name there.. How to do that..
Please help me. Thanks in advance.
@tvgece – You must use OAUTH. Refer to this page http://apiwiki.twitter.com/FAQ#HowdoIget%E2%80%9CfromMyApp%E2%80%9DappendedtoupdatessentfrommyAPIapplication for more information.
This is a great tutorial, but somethings wrong… on the applicationdelegat.m,, i replaced your fake info with my real twitter account, then clicked run/Console it shows up exactly the way the chearpy app, shows up, but it dosnt look like the one in the picture. Another words, i typed in correct info, and in the console, it didnt show my timeline. can you help?
This application crashes in the SDK 3.1.2 working fine in 3.0 and 3.1 .
crash over method authentication challege , please help me
Excellent! I fully understand — I did the typing
— and it was integrated and working in ~2 hours. I would suggest to others to add the following debug / trace statement until you are further along. It zeroed me in on my typing errors very quickly. Place the following two lines in connection:didReceiveData:
NSString *s = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@”%@”, s);
Other than that, the only bugs I found were the ones I introduced
I am a follower and I will “Donate” after my first full victory. Still $truggling …
Thanks for the tutorial, helped me a lot on figuring out the use of http connections.
Hi Brandon,
This is exactly the kind of tutorial I was looking for. Brillinat.
I was wondering when we will see part two?
Regards
Shaun
Brandon,
I had to run this a second time from scratch since my macbook took a dive and I did not have a recent enough backup. It was just as awesome the second time as the first.
You have a great style for concise detail and you make it meaningful.
-mobibob
hey was just wondering when are you gona be doing part 2?
Great Tutorial, it helped me a lot in my recent work!
I also recommend mobibob suggestion!
Cheers!
Pierre
Thanks, Dude.
This is what I am looking for these days.
Bookmarked your web!!
trying to create simple twitter client- what code would allow for different users to login with their username and passwords?
Great Code!
I’m a newbie to study xcode to produce program for iphone and mac..
Thanks,will follow ur instruction then
Vit (@freoniel)
Bangkok,Thailand
Very good and excellent article. I am waiting for the part 2 for this article which contains the formatted response of the result returned by the twitter sevice
Sir, i am a newbee on this and the iphone thing, but can you post/ tweet an image from the iphone using your code. I see that NSString is used, but is there any way to send images as tweets. I am really stuck on this one. Please forgive me for basic question. Thanks
Please cite your sources, 98% of this code is lifted directly from Apple’s documentation:
http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
@seriously – I am not claiming to have come up with the code 100%. Of course I would have had learn it from the Apple SDK.
Using NSURLConnection is a VERY standard process that doesn’t change much from project to project. What really changes is how you interact with the data you receive from the web. I am just showing how to use it to connect to Twitter.
So, stop being so CYNICAL and scouring the web looking for blogs where you can attempt to correct others in a sad attempt to boost your own self esteem.
This is THE BEST TUTORIAL EVER!! You have saved my life… and job!! Thank you!!!
Thank you for the great tutorial, saved me a lot of time for sure. I was wondering if you knew how to change the “via API” to “via [name of app]” when I post?
This was a really nice run-through of a Mac Twitter client. However, you may want to change the image in the tutorial so that each of the @synthesize tokens has a semicolon at the end. The code that you made available for download runs fine, but I kept getting a “syntax error before ‘AT_NAME’ token” error when running without the semicolons.
Still, this is an excellent tutorial.
Very Nice tutorial…Waiting for next step…how to parse it……Please post it early so that we can also feel like wow………
Thank you for the great tutorial, saved me a lot of time for sure. I was wondering if you knew how to change the “via API” to “via [name of app]” when I post?
Hey Bradon….when can we expect the next tutorial parsing of the response data of the series….waiting for this………Please reply me soon ……
Hi,
Could u pls tell me what is the need to register our app in twitter and also the need for oAuth process as mentioned in dev.twitter.com… Bcoz I dont see u having done any of these and when i used your code with few modications in my app, I could post a message form my app onto twitter succesfuuly…So whats the need for all those steps mentioned in dev.twitter.com???
This tutorial is quite useful but you avoid to explain the important stuff. I do want to understand not to just copy your code… For instance what does the code within connectionDidFinishLaunching mean? Could you explain that?
Cheers
Hello, very nice tutorial. Could you explain a bit more on the -(void)connectionDidFinishLoading:(NSURLConnection *)connection method of the TwitterRequest? I think that the following lines:
if(delegate && callback)
{
if([delegate respondsToSelector:self.callback])
{
[delegate performSelector:self.callback withObject:receivedData];
}
require a bit more explaining.
Thanks
And where is the second part?
Thank you so much for the post!!! im new to iphone and i’ve been lookin all over the internet to find a tutorial to help me out, and tell me the methods used so i can corelate them and that is what this post did to me
thank you soo soo soo much