我有一个包含 10 个 URL 的 NSMutableArray,我需要从中获取 HTTP header 。
下面是我的代码:
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"OST"];
[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];
}
当前 结果:所有请求都同时发送到服务器。
预期结果:想在得到响应后发送一个请求到服务器我想在后台发送另一个请求。
有什么建议吗?
重构您的代码以使用 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"OST"];
[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];
}
];
}
}
(完成 block 的语法可能不完全正确。我对带参数的 block 的语法有点挣扎。)
关于ios - 一一调用NSURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23805923/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |