Update View Controller After connectionDidFinishLo

2019-09-06 13:55发布

I am trying to load web content asynchronously. I am not sure how to update labels/other content in my view controller once the connectionDidFinishLoading method is called. In the sample below, I am just trying to update a label to show that the content has loaded. How would I do this? Thank you!

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[responseData
                                                   length]);
    NSString *txt = [[NSString alloc] initWithData:responseData encoding: 
    NSASCIIStringEncoding];

    label.text = @"DISPLAY THIS WHEN FINISHED";  
}

I have been told to let my viewController be the NSURLConnectionDelegate and then to will run the fetchData method from the viewDidLoad and then use the data you get the data for us when it is fetched in the connectionDidFinishLoading. Anyone know where to begin? Thanks!

1条回答
三岁会撩人
2楼-- · 2019-09-06 14:53

As Ramy correctly pointed you must update your UI on the main thread, then :

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
   NSLog(@"Succeeded! Received %d bytes of data",[responseData length]);
   NSString *txt = [[NSString alloc] initWithData:responseData 
                                         encoding: NSASCIIStringEncoding];

  NSString *text = @"DISPLAY THIS WHEN FINISHED";
  [label performSelectorOnMainThread:@selector(setText:) withObject:text waitUntilDone:NO]
}
查看更多
登录 后发表回答