Diving into the Twitter Stream



Hey iCoders. As I posted earlier I recently made an iPad app called TweetMapper. I just put out a new release of the app with a big new feature. The app now has a scrolling timeline of the tweets it is seeing as they come in. In order to make this app I took advantage of the Twitter Stream API that is provided by twitter. This API creates a persistent connection between the Twitter servers and your application. We will essentially start a stream of incoming NSData object to an NSURLConnection that you create querying the stream. We will look into the different search parameters which can be passed into the request, the way in which our code responds to authentication requests from Twitter, and the logic we must use to ensure that the data we have received is a complete XML element and not chopped off. There are three major steps to taking advantage of this in your app.



  1. Create an NSURLConnection to request an XML response from the Stream.

  2. Create a parameter string for the HTTP Body.

  3. Respond to the authentication challenge with user credentials.

  4. Append the data as it comes in and when a complete element is received parse the Tweets.


So lets dive in.


Creating the Class


The first thing that we need to do is establish a connection with the Twitter stream. I will not be creating a Twitter client class that can be plugged into any application you choose. You will be able to find the class as a download at the end of the post. We will call the class TwitterStreamClient. Lets first define the header file of the class.



#import
#import "TouchXML.h"
#import "Tweet.h"