2013-02-26 59 views
2

我正在构建一个登录模块,用户输入的凭据在后端系统中进行验证。我正在使用异步调用来验证凭据,并且在用户通过身份验证后,我使用方法presentViewController:animated:completion继续下一个屏幕。问题是presentViewController方法启动需要花费一些时间,直到出现下一个屏幕。恐怕我之前拨打sendAsynchronousRequest:request queue:queue completionHandler:的电话会以某种方式造成副作用。UIViewController presentViewController:动画:完成 - 需要4到6秒才能启动

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

第一: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]; 

任何帮助表示赞赏。

谢谢, 马科斯。

+0

那么你是否从完成块中调用表示代码? – 2013-02-26 00:34:27

+0

是的,我正在从完成块打电话给它 – vilelam 2013-02-26 00:35:52

回答

10

这是从后台线程操纵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]; 
    }); 
} 

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

+0

谢谢卡尔!你是男人!它为我节省了很多时间。 – vilelam 2013-02-26 00:56:04

+0

@vilelam谢谢,很高兴它帮助! – 2013-02-26 01:10:35

相关问题