-1

I've buttons in the dynamic cells of my UITableViewController. I've put them there programmatically with the code below. If I press a button now the UITableView disappears and I get a blank screen. When I go back a ViewController and go again to the UITableViewController all seems normal + the URLConnection did its job. What is wrong with my code?

UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self action:@selector(voteButton:) forControlEvents:UIControlEventTouchDown];
button.frame = CGRectMake(276, 0, 44.0, 44.0);
[cell.contentView addSubview:button];

The method it triggers is the voteButton:

- (void) voteButton:(UIButton *) sender {

    NSString *urlstring = [NSString stringWithFormat:@"http://www.someurl.com", (long)sender.tag];
    NSString *webStringURl = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURL *jsonFileUrl = [NSURL URLWithString:webStringURl];

    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];

    [NSURLConnection connectionWithRequest:urlRequest delegate:self];

    [self.tableView reloadData];
}

How can I reload the UITableView after the button is pressed?

ANSWER

The NSURLConnection wasn't finished before the TableView was reloaded so it couldn't show anything. I've put the [self.tableview reloadData]; in the function with connectionDidFinishLoading and now the button press is working.

Tom Spee
  • 9,209
  • 5
  • 31
  • 49

1 Answers1

1

Welcome to the world of asynchronous networking. The button calls

[NSURLConnection connectionWithRequest:urlRequest delegate:self]

Now a connection starts. But it does not yet end. It doesn't end until the delegate is told that it ends. So if you want to do something when the connection has finished doing whatever it is doing, do it in response to an NSURLConnection delegate message.

Your call to reloadData is way too soon, because the connection has only just started - it has not yet ended (in fact, it probably hasn't even started yet). It sounds from your description like there has been time to wipe out your data but not yet time to replace it!

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Okay I get what you're saying but I've multiple NSURLConnections in my UITableViewController, how does the function connectionDidFinishLoading now which NSURLConnection just finished? – Tom Spee Oct 15 '14 at 20:39
  • @speetje33 create the NSURLConnection as a variable for the whole .m file. Then when it finishes loading, check that the url request is equal to the variable. Or you can do a synchronous request if it is only small amounts of data – Ignacy Debicki Oct 15 '14 at 20:48
  • Thanks, I got it working. I followed these instructions: [link](http://stackoverflow.com/questions/9062393/how-can-we-handle-multiple-nsurlconnection-in-iphone-xcode) – Tom Spee Oct 15 '14 at 20:54