I’m currently working on parsing tweets from Twitter in an iOS application. My app currently can perform a search using the search.twitter.com/search.json?... API call, and my app can parse these tweets and select all of the data I want for each tweet. I’m at the phase now where I’m trying to fetch the user’s timeline, but I can’t seem to find a steady way to parse the returned object from the user’s timeline API call.
With the search feature (example returned object at the bottom of: https://dev.twitter.com/docs/api/1/get/search) I can parse by selecting valueForKey:(@"results") and loop through all of those results like so:
//jSONText is the returned result from the API in NSDictionary format
NSArray *resultTweetsJSON = [jSONText valueForKey:(@"results")];
for (int tweetIndex=0; tweetIndex<[resultTweetsJSON count]; tweetIndex++) {
//Loop through and pull out raw tweet content for a specific tweet
NSString *rawTweetContent = [resultTweetsJSON objectAtIndex:tweetIndex];
//Build a custom tweet object using that content
Tweet *singleTweet = [[Tweet alloc] initWithResultsContent:rawTweetContent];
}
I was hoping that I could perform the same or similar thing, but I can’t seem to find a good key to use with the returned data from the timeline (example returned data near the bottom of: https://dev.twitter.com/docs/api/1/get/statuses/user_timeline).
As you can see, the user_time result set doesn’t include a nice “results” key that I can query from.
How can I easily select and parse the data from a call to the Get/Statuses/User_Timeline Twitter API and have it converted into an NSArray so that I can loop through and pull out the tweets? Everything online seems to use old techniques. I found this tutorial but it looks like it takes the response from Twitter as an NSData object rather than an NSDictionary object, and I believe NSDictionary is the latest way to do it.
Here’s something I thought might work:
//No valueForKey to use, so perhaps use ""?
NSArray *timeline = [jSONText valueForKey:(@"")];
for (int i=0; i<[timeline count]; i++) {
//Looping through each "object" of the timeline, grab the tweet content then fill user content
//Grab the "user" object from the timeline object we're looking at
NSString *rawUserContent = [[timeline objectAtIndex:i] valueForKey:(@"user")];
//NSString *rawUserContent = [timeline valueForKey:(@"user")]; - Maybe this?
//Do whatever else I need to do here...
}
After a couple of days, I found out I was just over-complicating the problem. All I needed to do was convert to an array and parse accordingly.
I then wrapped all of the above code in an if statement. If the user is performing a search (using Twitter’s search API) I perform all of the code in my question above, and if the user is performing a select from the user’s timeline, I perform all of the code in this answer.
Works like a charm and I can now properly parse both JSON returned results, all I needed to do was convert the dictionary to an array.