Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

CellTableView With Twitter API won't Display Data

Hello guys, I'm currently doing a practice for twitter API. Currently, i had a problem to populate a search hashtag results to tableview cellForRowAtIndexPath method. Below is my code.

My Header Code :

@interface TableViewController : UITableViewController<UITableViewDataSource,UITableViewDelegate> @property (nonatomic,strong) NSArray *array; @end

My Implementation Code :

#import "TableViewController.h"
#import <Social/Social.h>
#import <Accounts/Accounts.h>

@interface TableViewController ()



@end

@implementation TableViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self getDataFromTwitter];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    NSDictionary *dataDictionary = self.array[indexPath.row];
    NSLog(@"data fromtwitter : %@", dataDictionary[@"count"]);
    NSLog(@"data result: %@", self.array);
    cell.textLabel.text = dataDictionary[@"text"];

    return cell;
}

- (void)getDataFromTwitter {

    // 1. set an URL
    NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/search/tweets.json"];

    // 2. set NSMutableArray For Parameter
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc] init];
    [parameter setObject:@"%23MH370" forKey:@"q"];
    [parameter setObject:@"10" forKey:@"count"];
    [parameter setObject:@"popular" forKey:@"result_type"];

    //3. set ACAccountStore & ACAccountType

    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {

        if (granted == YES) {
            NSArray *accountArray = [accountStore accountsWithAccountType:accountType];

            if ([accountArray count] > 0) {

                ACAccount *twitterAccount = [accountArray lastObject];

                // guna slrequest to get data from twitter

                SLRequest *getRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:parameter];


                // set twitter account
                [getRequest setAccount:twitterAccount];

                [getRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {

                    NSString *output = [NSString stringWithFormat:@"HTTP response status %i : ", [urlResponse statusCode]];
                    NSLog(@"Output : %@", output);
                    self.array = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];


                    if (self.array.count != 0) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //[self.tableView reloadData];
                        //   NSLog(@"search result: %@", self.array);
                         });
                    }

                }];

            }
        }

    }];

}

@end

I don't know where is the error because i didn't get any error when i running the apps. But my apps break when it's running. Here is the image :

alt text

6 Answers

From what I can tell it looks like you didn't initialize the array in the viewDidLoad method. array = [NSArray alloc] init];

Also "NSDictionary *dataDictionary = self.array[indexPath.row]" try changing that to NSDictionary *datDictionary = [self.array objectAtIndex:indexPath.row];

Let me know if that helps or if I am completely wrong. :-)

I already tried with your suggestion but it still gave a same error on the console.

Here is the error :

2014-03-12 19:57:11.990 twitterSearch[3069:a0b] -[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance 0xa45fd00
2014-03-12 19:57:11.992 twitterSearch[3069:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance 0xa45fd00'

NSJSONSerializer may have returned a dictionary. Store the result in an id instead of an NSArray first, and then either NSLog it or set a breakpoint to check its content.

Edit: Aha! Was typing mine while you responded to Patrick. Looks like the serializer indeed returned an NSDictionary instead of an NSArray according to your error message.

Yup - that is what I found when I went searching. Stack Overflow

i'm really confusing right now.I tried to comment out [self.tableView reloadData] and the console didn't give me any error. I also try to NSLog self.array after self.array = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error]; and i got a list on JSON in console. But still in my tableView i can't see any output from JSON.

Are you setting the JSON response to a string? or an array?

an array.

The response is sending an NSDictionary.

We have to change this: @property (nonatomic,strong) NSArray *array; to this: @property (nonatomic,strong) NSDictionary *tweets;

Then we have to take out the array of Statuses from the dictionary:

Change this.. NSDictionary *dataDictionary = self.array[indexPath.row]; To this:

for (NSDictionary *tw in _tweets) { NSArray *statuses = [_tweets objectForKey:@"statuses"]; //And finally take the text from each tweet. for (NSDictionary *text in statuses) { NSLog(@"Tweet:: %@", [text objectForKey:@"text"]); } } Remember to uncomment your [self.tableview reloadData];

Grettings.