NSURLConnection在完成所有处理后发送请求
我有一个发送请求的嵌套循环。NSURLConnection在完成所有处理后发送请求
-(void) download
{
for(NSString *id in array)
{
//init with request and start the connection
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request deletegate:self];
[conn start];
}
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data
{
//enter here secondly
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
//enter here last, after finish the for loop
//my intention is use the downloaded data to do something before sending a new request.
}
的问题是,我想进入"-(void) connectionDidFinishLoading:(NSURLConnection *) connection"
先在再次发送请求循环之前。
但目前它会完成for循环并发送所有请求,然后输入到"-(void) connectionDidFinishLoading:(NSURLConnection *) connection"
。
你应该尝试这NSURLConnection的是在iOS9
弃用for (NSString *URL in URLArray) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// check error and/or handle response here
}];
[task resume];
}
,并使用dispatch_group_t group = dispatch_group_create();
添加行for循环dispatch_group_enter(group);
将调用
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// Request Finish
});
为你的目标
在你的情况下,你需要尝试阻止功能,因为根据你的要求,你需要响应第一个连接的另一个请求。
for(NSString* url in array)
{
// Generate a NSURLRequest object from the address of the API.
NSURL *url = [NSURL URLWithString:urlLink];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Send the request asynchronous request using block!
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Error in updateInfoFromServer: %@ %@", error, [error localizedDescription]);
} else if (!response) {
NSLog(@"Could not reach server!");
} else if (!data) {
NSLog(@"Server did not return any data!");
} else {
[self doStuffWithData:data];
}
}];
}
URL负载不是同步操作(或至少不应该是同步完成的),因为它可能需要长达90秒的只是一个DNS查找失败,而且几乎无限长,如果服务器保持运球出数据。如果你阻止主线程的时间甚至只有这个时间的一小部分,iOS会杀死你的应用程序。
而不是在循环中调度请求并等待它们完成,您需要安排第一个请求(并且只有第一个请求)。然后,在您的connectionDidFinishLoading:
方法(也可能是您的connection:DidFailWithError:
方法)中,安排下一个请求。这样说,除非你仍然需要支持iOS 6/10.8和更早的版本,否则你应该使用NSURLSession。 (相同的一般建议适用;代理方法名称被改变以保护有罪)。
[NSURLConnection sendSynchronousRequest:request returningResponse:Response error:nil] –
您可以使用带有addDependency或MaxConcurrentOperation的NSOperationQueue。 –
@PKT我认为你的解决方案对我来说已经足够了。谢谢 – user1151874