NSURL连接多个异步连接



我正试图弄清楚为什么我的UI在加载所有NSURLConnection之后才更新。

我基本上是加载一个"登录"请求,接收响应,然后调用:

[[NSNotificationCenter defaultCenter] postNotificationName:@"connectionFinishedLoading" object:[NSMutableDictionary dictionaryWithObject:dataForConnection forKey:conn.tag]]

我在代码的其他地方收到通知,它调用:

[self.loginViewController dismissViewControllerAnimated:YES completion:nil];

以及NSLog,所以我知道它实际上在正确的时间使用了这个方法,只是在其他NSURLConnection(基本上是在对话框隐藏的同时启动的)完成之后,视图控制器才被解除。

在过去的几个小时里,我一直在研究这个问题,我仍然不确定我用来创建/发送请求的代码是否异步工作:

-(void)initGET:(NSString *)url queryString:(NSString *)theQueryString tag:(NSString *)tag{
if([Utils CanConnectToURL:url]){
//NSLog(@"url: %@", url);
//NSLog(@"queryString: %@", theQueryString);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", url, theQueryString]]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setTimeoutInterval:60*10];
URLConnection *connection = [[URLConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag];
if(connection){
[receivedData setObject:[NSMutableData data] forKey:connection.tag];
[conns addObject:connection];
}
else
[receivedData setObject:NSLocalizedString(@"ConnectionError", nil) forKey:connection.tag];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"NoInternetConnectionTitle", nil) message:NSLocalizedString(@"NoInternetConnectionMessage", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
alert.tag = 999;
[alert show];
}

}

我的猜测是,它已经是异步的,因为我在第一个连接完成后直接启动了另外3个NSURLConnection,我的日志显示,其他3个连接基本上都是在同一时间启动的,然后都在稍后完成。如果它只是同步的,当然,1个连接会开始,然后结束,然后第二个连接开始/结束,以此类推…

有人知道为什么我的UI不能正确更新吗?如果是这样的话,一个好的解决方案是什么?我已经看了一点NSOperationQueue,但在使用NSNotificationCenter传递消息/对象时,使用它似乎开始引发其他问题,我在URLConnectionManager类中经常使用NSNotificationCenter。

谢谢!

Mike

URLConnection不是标准的NSURLConnection。如果没有看到URLConnection的实现,很难判断它是否是异步的。

此外,当您收到连接已完成的通知时,您是如何更新UI的?

最新更新