我正在使用Web服务进行身份验证的项目需要登录表单。我没有问题连接到服务器,但似乎NSURLSession阻止了我的用户界面,并且经过大量调试后,我真的不知道为什么。
为简单起见,以下是我的代码:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"example.com/service"]];
//1
//_sessionLogin = [NSURLSession sessionWithConfiguration:sessionConfigurationLogin delegate:self delegateQueue:nil];
//2 //Whether I use 1 or 2, it acts the same way
_sessionLogin = [NSURLSession sharedSession];
NSURLSessionDataTask *sessionDataTaskLogin = [_sessionLogin dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(!error)
{
NSLog(@"loginWithSuccess");
UIAlertView *alertError = [[UIAlertView alloc] initWithTitle:@"Login ok" message:@"ok" delegate:self cancelButtonTitle:@"Close" otherButtonTitles: nil];
[alertError show];
}
}];
//Begin login request
[sessionDataTaskLogin resume];
_sessionLogin是一个NSURLSession
由于与服务器的连接速度很快,因此在我按下登录按钮后,NSLog(@“ loginWithSuccess”)几乎立即出现,但是显示UIAlertView大约要花10秒钟的时间(很长一段时间)。而且我也无法与UI进行交互。
在此先感谢您提供的所有解决方案。
您的完成块未在主线程上运行。由于UI更新必须在主线程上进行,因此您应该将警报视图分派到主队列,然后立即看到它。
NSURLSessionDataTask *sessionDataTaskLogin = [_sessionLogin dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSLog(@"loginWithSuccess");
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertError = [[UIAlertView alloc] initWithTitle:@"Login ok" message:@"ok" delegate:self cancelButtonTitle:@"Close" otherButtonTitles: nil];
[alertError show];
});
}
}];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句