逐个调用NSURLConnection

时间:2014-05-22 11:45:43

标签: ios objective-c nsurlconnection

我有一个NSMutableArray,其中包含10个URL,我需要从中获取HTTP标头。

以下是我的代码:

for(int i=0; i<[contactsArray count];i++)
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSString *reqstr=[NSString stringWithFormat:@"%@",urlString ];
    [request setURL:[NSURL URLWithString:reqstr]]; 
    NSLog(@"requested url is %@",reqstr);

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:[mDict JSONData]];

    NSURLConnection *theConnection=[[NSURLConnection alloc]initWithRequest:request         delegate:self startImmediately:YES];

}

当前 结果:所有请求一次转到服务器。

预期结果:想要在收到回复后向服务器发送一个请求我想在后台发送另一个请求。

有什么建议吗?

2 个答案:

答案 0 :(得分:4)

重构您的代码以使用sendAsynchronousRequest:queue:completionHandler:方法,并在当前帖子完成后调用自身:

将您的计数移动到实例变量。我们称之为currentItem。您的代码可能如下所示:

- (void) postItems;
{
  while (currentItem < [contactsArray count)
  {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    NSString *reqstr=[NSString stringWithFormat:@"%@",urlString ];
    [request setURL:[NSURL URLWithString:reqstr]]; 
    NSLog(@"requested url is %@",reqstr);

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:[mDict JSONData]];

    [NSURLConnection sendAsynchronousRequest: request 
      queue:  dispatch_get_main_queue ()
      completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error)
      {
        //check for errors
        //save any response data

        //Now trigger the next request
        currentItem++
        [self postItems];
      }
    ];
  }
}

(完成块的语法可能不完全正确。我对使用参数的块的语法略有不同。)

答案 1 :(得分:0)

您使用ASIHTTPRequest异步调用:

Link for ASIHTTPRequest

然后写如下代码:

for(int i=0; i<[contactsArray count];i++)
{

NSURL* url = [NSURL URLWithString:urlString];
__block ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];

[request setCompletionBlock:^
 {

              //NEED SOMEHOW RETURN TRUE IF SUCESSED

 }];

[request setFailedBlock:^
 {
     //NEED RETURN FALSE
 }];

[request startAsynchronous];

}