UIViewController presentViewController:animation:完成 – 需要4到6秒才能启动

我正在构build一个login模块,用户input的凭据在后端系统中进行validation。 我正在使用asynchronous调用来validation凭据,并且在用户通过身份validation之后,我使用presentViewController:animated:completion方法进入下一个屏幕presentViewController:animated:completion 。 问题是, presentViewController方法启动需要花费一些时间,直到出现下一个屏幕。 恐怕我先前调用sendAsynchronousRequest:request queue:queue completionHandler:会以某种方式产生副作用。

只是为了确保当我说4 – 6秒后,在命令presentViewController:animated:completion开始。 我说这是因为我正在debugging代码并监视调用方法的时刻。

首先:调用NSURLConnection方法:

 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) 

第二: UIViewController方法被称为采取不正常的时间运行

 UIViewController *firstViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstView"]; [self presentViewController:firstViewController animated:YES completion:nil]; 

任何帮助表示赞赏。

谢谢,马科斯。

这是从后台线程操纵UI的典型症状。 你需要确保你只在主线程上调用UIKit方法。 完成处理程序不保证在任何特定的线程上调用,所以你必须做这样的事情:

 [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]; }); } 

这保证你的代码在主线程上运行。