Delay when updating view in the completionHandler of an async HTTP request

后端 未结 3 1329
生来不讨喜
生来不讨喜 2021-01-06 14:46

In my app when the user presses a button I start a HTTP asynchronous request (using [NSURLConnection sendAsynchronousRequest...]) and change the text of U

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 15:08

    This could happen because all UI stuff should be called in a main queue. Try this:

    - (IBAction)requestStuff:(id)sender 
    {
        NSURL *url = [NSURL URLWithString:@"http://stackoverflow.com/"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
    
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
         ^(NSURLResponse *response, NSData *data, NSError *error) 
         {
             NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;          
    
             dispatch_async(dispatch_get_main_queue(), ^{
                 exampleLabel.text = [NSString stringWithFormat:@"%d", httpResponse.statusCode];
             });
         }];    
    }
    

提交回复
热议问题