gpt4 book ai didi

ios - 一一调用NSURLConnection

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:43:06 24 4
gpt4 key购买 nike

我有一个包含 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:@"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];

}

当前 结果:所有请求都同时发送到服务器。

预期结果:想要在收到响应后发送一个请求以切断我想在后台发送另一个请求。

有什么建议吗?

最佳答案

重构您的代码以使用 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];
}
];
}
}

(完成 block 的语法可能不完全正确。我对带参数的 block 的语法有点纠结。)

关于ios - 一一调用NSURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23805923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com