UIViewController presentViewController:animated:completion - 需要4到6秒才能启动

vil*_*lam 2 objective-c uiviewcontroller ios

我正在构建一个登录模块,其中用户输入的凭据在后端系统中得到验证.我正在使用异步调用来验证凭据,在用户通过身份验证后,我使用该方法进入下一个屏幕presentViewController:animated:completion.问题是,presentViewController启动方法需要花费很长时间才能显示下一个屏幕.我担心我之前的电话会以sendAsynchronousRequest:request queue:queue completionHandler: 某种方式产生副作用.

只是为了确保我说命令presentViewController:animated:completion启动后4-6秒.我是这么说的,因为我正在调试代码并监视调用方法的时刻.

第一:该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)
Run Code Online (Sandbox Code Playgroud)

第二种:UIViewController方法被称为运行异常时间

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

[self presentViewController:firstViewController animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.

谢谢,马科斯.

Car*_*zey 11

这是从后台线程操纵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];
    });
}
Run Code Online (Sandbox Code Playgroud)

这可以保证您的代码在主线程上运行.