我正在构建一个登录模块,其中用户输入的凭据在后端系统中进行验证。我使用一个异步调用来验证凭据,在用户通过身份验证后,我使用presentViewController:animated:completion方法进入下一个屏幕。问题是,启动presentViewController方法需要一段时间才能显示下一个屏幕。我担心我之前对sendAsynchronousRequest:request queue:queue completionHandler:的调用在某种程度上产生了副作用。
只是为了确保我说的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];任何帮助都是非常感谢的。
谢谢,马科斯。
发布于 2013-02-26 08:40:29
这是从后台线程操作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];
});
}这保证了您的代码在主线程上运行。
https://stackoverflow.com/questions/15079232
复制相似问题