基本上我想要一种在循环中多次发出 NSURLRequest 直到满足某个条件的方法。我正在使用休息 api,但休息 api 一次最多只能允许 1,000 个结果。因此,如果我有,假设总共有 1,500 个,我想请求获得前 1,000 个,然后我需要通过另一个几乎完全相同的请求来获得其余的,除了 startAt: 参数不同(所以我可以从 1001 到 1500 .我想在一个while循环中设置它(当我完成加载所有数据时)并且正在阅读有关信号量但它没有像我预期的那样工作。我不知道我有多少结果直到我发出第一个请求。可能是 50、1000 或 10,000。
这是代码:
while(!finishedLoadingAllData){
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLRequest *myRequest = [self loadData: startAt:startAt maxResults:maxResults];
[NSURLConnection sendAsynchronousRequest:myRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if(error){
completionHandler(issuesWithProjectData, error);
}
else{
NSDictionary *issuesDictionary = [[NSDictionary alloc] initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]];
[issuesWithProjectData addObjectsFromArray:issuesDictionary[@"issues"]];
if(issuesWithProjectData.count == [issuesDictionary[@"total"] integerValue]){
completionHandler([issuesWithProjectData copy], error);
finishedLoadingAllData = YES;
}
else{
startAt = maxResults + 1;
maxResults = maxResults + 1000;
}
}
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
基本上我想让while循环一直等到完成块完成。然后,只有这样,我才希望 while 循环检查我们是否拥有所有数据(如果没有,则使用更新的 startAt 值/maxResults 值发出另一个请求。
现在它只是挂在dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
我做错了什么或者我需要做什么?也许信号量是错误的解决方案。谢谢。