UIViewController presentViewController:animated:co

2019-05-23 04:37发布

I'm building a login module where the credentials entered by the user are validated in a backend system. I'm using an asynchronous call to validate credentials and after user has been authenticated I proceed to next screen using the method presentViewController:animated:completion. The problem is that the presentViewController method launching is taking an abornal time until presenting the next screen. I’m afraid that my previous call to the sendAsynchronousRequest:request queue:queue completionHandler: is somehow creating a side effect.

Just to make sure when I say 4 – 6 seconds is after the command presentViewController:animated:completion is started. I'm saying it because I’m debugging the code and monitoring the moment where the method is called.

First: the NSURLConnection method is called:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)

Second: UIViewController method is called taking an abnormal time running

UIViewController *firstViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstView"];

[self presentViewController:firstViewController animated:YES completion:nil];

Any help is appreciated.

thanks, Marcos.

1条回答
放荡不羁爱自由
2楼-- · 2019-05-23 05:23

This is a classic symptom of manipulating the UI from a background thread. You need to make sure you only call UIKit methods on the main thread. The completion handler isn't guaranteed to be called on any particular thread so you must do something like this:

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *firstViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstView"];
        [self presentViewController:firstViewController animated:YES completion:nil];
    });
}

This guarantees your code runs on the main thread.

查看更多
登录 后发表回答