close
Code, Nerdyness, and Nonsense Code, Nerdyness, and Nonsense
Search
Objective-C Programming Tutorial – Creating A Twitter Client Part 1

twitter-logo

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.

screenshot_01

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



screenshot_02

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.

screenshot_03

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:

screenshot_04

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:

screenshot_05

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:

screenshot_06

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:

screenshot_01

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:

screenshot_08

Pretty simple… Stay with me, we have 3 more delegate methods to implement. Add the following code:

screenshot_09

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…

screenshot_10

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:

screenshot_11

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.

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:

screenshot_01

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:

screenshot_03

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.

screenshot_05

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!

arrow43 Comments

  1. 7 mos, 3 wks ago

    This is pretty solid. Looking forward to the next one.

  2. David
    7 mos, 3 wks ago

    Very nice! Thanks

  3. 7 mos, 3 wks ago

    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

  4. Austin in Austin
    7 mos, 3 wks ago

    This is exactly what I am looking for! I am writing an iPhone app that will use the Twitter API. Good stuff Brandon! kthx

  5. 7 mos, 3 wks ago

    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!

  6. 7 mos, 2 wks ago

    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

  7. tetsushi
    7 mos, 2 wks ago

    thanks for supporting novice programmers like me. This tutorial helped alot. Thanks from Japan.

  8. 7 mos, 1 wk ago

    Hi Brandon,

    This is an awesome tutorial. I have been searching high and low for something like this on google. Thanks a lot man!

  9. Vic
    7 mos ago

    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.

  10. Mike
    7 mos ago

    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…

  11. Mike
    7 mos ago

    I answered my own question. It works great with the iPhone SDK.

  12. Mike
    6 mos, 4 wks ago

    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.

  13. 6 mos, 3 wks ago

    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

  14. 6 mos, 3 wks ago

    great tutorial!

  15. Zimmen
    6 mos, 3 wks ago

    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];
    }

  16. 6 mos, 3 wks ago

    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!

  17. 6 mos, 3 wks ago

    It would, I would suggest doing a [tr release]. I’ll update this post when I put up part 2.

  18. 6 mos, 2 wks ago

    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?

  19. 6 mos, 2 wks ago

    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.

  20. 6 mos, 2 wks ago

    Ah! Thanks.

    It was driving me crazy.

  21. 6 mos, 2 wks ago

    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.

  22. 6 mos, 2 wks ago

    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.

  23. 6 mos, 2 wks ago

    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.

  24. 6 mos, 2 wks ago

    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.

  25. 6 mos, 2 wks ago

    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.

  26. Mhike Miranda
    6 mos, 2 wks ago

    Very nice tutorial, learn a lot. I’ll bookmark it and looking forward to part 2.

  27. Ram
    5 mos, 3 wks ago

    Great tutorial, Brandon. Have you considered writing one with OAuth.

  28. tvgece
    5 mos ago

    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.

  29. 5 mos ago

    @tvgece – You must use OAUTH. Refer to this page http://apiwiki.twitter.com/FAQ#HowdoIget%E2%80%9CfromMyApp%E2%80%9DappendedtoupdatessentfrommyAPIapplication for more information.

  30. 4 mos, 3 wks ago

    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?

  31. Crystal
    3 mos, 2 wks ago

    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

  32. mobibob
    3 mos, 2 wks ago

    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 …

  33. Jose Muanis
    3 mos, 2 wks ago

    Thanks for the tutorial, helped me a lot on figuring out the use of http connections.

  34. Shaun Savage
    2 mos, 3 wks ago

    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

  35. 2 mos, 3 wks ago

    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

  36. xscript
    2 mos, 1 wk ago

    hey was just wondering when are you gona be doing part 2?

  37. 2 mos, 1 wk ago

    Great Tutorial, it helped me a lot in my recent work!

  38. 2 mos, 1 wk ago

    I also recommend mobibob suggestion!

    Cheers!
    Pierre

  39. 2 mos ago

    Thanks, Dude.
    This is what I am looking for these days.
    Bookmarked your web!!

  40. 1 mo, 3 wks ago

    trying to create simple twitter client- what code would allow for different users to login with their username and passwords?

  41. 1 mo, 3 wks ago

    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

  42. Hamid
    1 mo, 1 wk ago

    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

  43. maxfiresolutions
    1 mo ago

    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

Leave A Comment