Search code examples
iosuitableviewasihttprequest

ios - ASIHTTPREQUEST populating uitableview with json data


I've been reading for hours and I can't figure out why my table won't reload itself with the updated data, here is the request I am making in block form:

 ASIHTTPRequest *_request= [ASIHTTPRequest requestWithURL:url];
__weak ASIHTTPRequest *request = _request;
request.requestMethod = @"POST";
[request addRequestHeader:@"Content-Type" value:@"application/json"];


[request setDelegate:self];
[request setCompletionBlock:^{
    NSString *responseString = [request responseString];
    NSData *responseData = [request responseData];
    NSLog(@"Response: %@", responseString);
    NSError* error;
    json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSLog(@"request finished");
    [CommMTable reloadData];


}];
[request setFailedBlock:^{
    NSError *error = [request error];
    NSLog(@"Error: %@", error.localizedDescription);
}];

[request startAsynchronous];

It gets the json object successfully as it is printed in my console but the table doesn't update!

here is my table pragma section

(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

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


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

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    NSDictionary *tempDictionary= [self.json objectAtIndex:indexPath.row];



    if(cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }


    cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
    cell.textLabel.text = [tempDictionary objectForKey:@"title"];


    return cell;
}

any help is appreciated, this is really frustrating :(


Solution

  • I found the problem, I was doing everything correctly (json format and stuff were properly set). The problem was that for some reason the table got disconnected from it's delegate and datasource, for the people who had a similar problem try this solution.

    In the xib file just ctrl + drag the tableview to the File Owner and connect it to the delegate and datasource.

    or you can do it with just code if you don't like the interface builder with the following lines

    [myTableView setDataSource:self];
    [myTableView setDelegate:self];
    

    or

    self.tableView.delegate = self.tableDelegate;
    self.tableView.datasource = self.tableDelegate; 
    

    both either/or should work.