我正在使用 Objective-C 编写一个应用程序,需要发送 100 个网络请求,并且响应将在回调中处理。我的问题是,如何执行 web req0,等待回调,然后执行 web req1 等等?
感谢您的任何提示和帮助。
NSURL *imageURL = [[contact photoLink] URL];
GDataServiceGoogleContact *service = [self contactService];
// requestForURL:ETag:httpMethod: sets the user agent header of the
// request and, when using ClientLogin, adds the authorization header
NSMutableURLRequest *request = [service requestForURL:imageURL
ETag: nil
httpMethod:nil];
[request setValue:@"image/*" forHTTPHeaderField:@"Accept"];
GTMHTTPFetcher *fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
fetcher.retryEnabled = YES;
fetcher.maxRetryInterval = 0.3;
fetcher.minRetryInterval = 0.3;
[fetcher setAuthorizer:[service authorizer]];
[fetcher beginFetchWithDelegate:self
didFinishSelector:@selector(imageFetcher:finishedWithData:error:)];
}
- (void)imageFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *)error {
if (error == nil) {
// got the data; display it in the image view. Because this is sample
// code, we won't be rigorous about verifying that the selected contact hasn't
// changed between when the fetch began and now.
// NSImage *image = [[[NSImage alloc] initWithData:data] autorelease];
// [mContactImageView setImage:image];
NSLog(@"successfully fetched the data");
} else {
NSLog(@"imageFetcher:%@ failedWithError:%@", fetcher, error);
}
}
最佳答案
您不能简单地在循环中调用此代码,因为 GTMHTTPFetcher
异步工作,因此如您所见,循环将迭代并启动所有实例,没有任何延迟。
一个简单的选择是将所有 contact
放入一个可变数组中,从数组中取出第一个 contact
(将其从数组中删除)并启动第一个抓取器。然后,在 finishedWithData
回调中,检查数组是否包含任何内容,如果它确实删除第一项并开始获取它。通过这种方式,提取将一个接一个地连续运行。
一个更好但更复杂的解决方案是创建一个异步的 NSOperation
(网络上有各种指南),它开始获取并在完成之前等待回调。这种方法的好处是您可以创建所有操作并将它们添加到操作队列中,然后您可以设置最大并发计数并运行队列——这样您就可以同时运行多个提取实例。如果需要,您还可以暂停队列或取消操作。
关于ios - 按顺序发送 100 个 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29753443/