0

我有一个发送请求的嵌套循环。

-(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 循环中再次发送请求之前先输入。

但目前它将完成 for 循环并在 enter 之前将所有请求发送到"-(void) connectionDidFinishLoading:(NSURLConnection *) connection".

4

3 回答 3

1

你应该试试这个 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
});

为了你的目标

于 2016-04-27T06:27:42.247 回答
0

URL 加载不是同步操作(或者至少不应该同步完成),因为仅 DNS 查找失败就可能需要长达 90 秒,如果服务器不断运出数据则几乎无限长。如果你阻塞主线程的时间只是其中的一小部分,iOS 就会杀死你的应用程序。

您不需要在循环中安排请求并等待它们完成,而是需要安排第一个请求(并且只安排第一个请求)。然后,在您的connectionDidFinishLoading:方法(可能还有您的connection:DidFailWithError:方法)中,安排下一个请求。

话虽如此,除非您仍然需要支持 iOS 6/10.8 及更早版本,否则您可能应该使用 NSURLSession。(同样的一般建议也适用;更改了委托方法名称以保护有罪者。)

于 2016-05-02T04:53:35.047 回答
0

在您的情况下,您需要尝试阻止功能,因为根据您的要求,您希望第一个连接响应另一个请求。

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];
                           }
                       }];
}
于 2016-04-27T07:54:24.123 回答