This tutorial has moved! I have updated it to support Twitter’s Oauth, you can find the first tutorial in there series by clicking the link below
Creating A Twitter Client For OSX – Part 1
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:
[code=’c’][delegate performSelector:self.callback withObject:receivedData];[/code]
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.














