Question

Ok, I'm pretty new to this and been struggling with what you guys may feel is quite an easy exercise. I have trawled high and low and cannot find a good tutorial or walkthrough on how to do this. Basically, I am using the code below to obtain tweets and I only want the 'text' part of the tweet. How do I extract it out of the NSDictionary in order to use the 'text' key in a tableview? I have tried [dict objectForKey:@"text"] but it does not work - 'dict' does not seem to contain a 'text' attribute. Thanks in advance for any help.

// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
   @"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"] 
   parameters:nil requestMethod:TWRequestMethodGET];

// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
  if ([urlResponse statusCode] == 200) 
  {
    // The response from Twitter is in JSON format
    // Move the response into a dictionary and print
    NSError *error;        
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
    NSLog(@"Twitter response: %@", dict);                           
  }
  else
    NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
Was it helpful?

Solution

Yes there is an objectForKey@"text" but it is an array which means that every entry (tweet) has text (and several other attributes). So we've to loop through the tweets to get FOR every tweet the text.

In your .h file

         NSMutableArray *twitterText;

In your .m file

Do this somewhere in viewdidload

         twitterText = [[NSMutableArray alloc] init];

And now we can loop through your results. Paste this code where you've NSLog(@"Twitter response: %@", dict);

          NSArray *results = [dict objectForKey@"results"];

         //Loop through the results

         for (NSDictionary *tweet in results)
         {
             // Get the tweet
             NSString *twittext = [tweet objectForKey:@"text"];

             // Save the tweet to the twitterText array
             [twitterText addObject:(twittext)];

And for your cells in your tableView

         cell.textLabel.text = [twitterText objectAtIndex:indexPath.row];

I think that should be working.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top