Fill UITableView from json

I am trying to populate a UITableView data from a json result. I can get it to load from the plist array without any problems, and I can even see my json. The problem I am facing is that a UITableView will never see json results. please refrain from me as this is my first time with Objective-C.

In my .h file

 @interface TableViewViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> { NSArray *exercises; NSMutableData *responseData; } 

In my .m file

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return exercises.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //create a cell UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; // fill it with contnets cell.textLabel.text = [exercises objectAtIndex:indexPath.row]; // return it return cell; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { responseData = [[NSMutableData data] retain]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://url_to_json"]]; [[NSURLConnection alloc] initWithRequest:request delegate:self ]; // load from plist //NSString *myfile = [[NSBundle mainBundle] pathForResource:@"exercise" ofType:@"plist"]; //exercises = [[NSArray alloc] initWithContentsOfFile:myfile]; [super viewDidLoad]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [responseData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [responseData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Connection failed: %@", [error description]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; [responseData release]; NSDictionary *dictionary = [responseString JSONValue]; NSArray *response = [dictionary objectForKey:@"response"]; exercises = [[NSArray alloc] initWithArray:response]; } 
+4
source share
3 answers

You need to indicate that your table view is being reloaded. Try adding:

 [tableView reloadData]; 

at the end of your method is -connectionDidFinishLoading.

+14
source

Use

 [self.tableView reloadData]; 
+1
source

You may need to add the following line of code at the end of your connectionDidFinishLoading method:

 [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; 

This will update the UITableView in the main thread, since connectionDidFinishLoading is executing in another thread.

0
source

Source: https://habr.com/ru/post/1311772/


All Articles