NSURLConnection and SBJSon in AppDelegate

493 views Asked by At

I'm in xCode 4.2 using ARC and Storyboard (iOS 5). I suppose to put Tweets to my TableViewController. As I placed my NSURLConnection, everything goes fine and I have the response already in tweets(NSArray) in the delegate. The problem is it doesn't populate the table view. I am using SBJson for the received data. Am I missing something?

AppDelegate.m

#import "AppDelegate.h"
#import "TwitterViewController.h"
#import "SBJson.h"


@implementation AppDelegate

@synthesize window = _window;

@synthesize receivedData;
@synthesize tableViewController;
@synthesize tweets;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    tweets = [NSMutableArray array];
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"http://search.twitter.com/search.json?q={username}&rpp=5"]];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

    if (theConnection) {
        receivedData = [NSMutableData data];
    }
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{

    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);


    NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

    NSDictionary *results = [responseString JSONValue];

    NSArray *allTweets = [results objectForKey:@"results"];

    [tableViewController setTweets:allTweets];
}
@end

This is the delegate methods in my table view controller.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tweets count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"twitter";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    NSDictionary *aTweet = [tweets objectAtIndex:[indexPath row]];



    NSString *textFrom = [aTweet objectForKey:@"text"];
    cell.textLabel.text = textFrom;


    return cell;
}

I really need some advice.

1

There are 1 answers

0
ruelluna On BEST ANSWER

Table reload. Gosh! I learned!