我有一些请求需要逐个触发,具体取决于之前的响应。
这与NSOperation
非常直接,并试图找出答案
什么是Sessions& amp; AFNetworking> = 3.0
-(void)startGet
{
NSString *urlStr = [NSString stringWithFormat:@"https://test.com/test?%ld",(long)test];
NSURL *URL = [NSURL URLWithString:urlStr];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSLog(@"NUMBER: %ld",(long)test);
[manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"task: %@",task.currentRequest.URL.absoluteString);
} failure:^(NSURLSessionTask *operation, NSError *error) {
//NSLog(@"Error: %@", error);
}];
}
- (void)viewDidLoad {
[super viewDidLoad];
for (int i=0; i<10; i++)
{
test = i;
[self startGet];
}
}
我想要的日志是:
https://test.com/test?0
https://test.com/test?1
https://test.com/test?2
https://test.com/test?3
https://test.com/test?4
https://test.com/test?5
https://test.com/test?6
...
我尝试过的事情:
...
dispatch_group_t serviceGroup = dispatch_group_create();
...
-(void)startGet
{
NSString *urlStr = [NSString stringWithFormat:@"https://test.com/test?%ld",(long)test];
NSURL *URL = [NSURL URLWithString:urlStr];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSLog(@"NUMBER: %ld",(long)test);
dispatch_group_enter(serviceGroup);
[manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"task: %@",task.currentRequest.URL.absoluteString);
dispatch_group_leave(serviceGroup);
} failure:^(NSURLSessionTask *operation, NSError *error) {
dispatch_group_leave(serviceGroup);
//NSLog(@"Error: %@", error);
}];
dispatch_group_wait(serviceGroup,DISPATCH_TIME_FOREVER);
}
虽然请求以正确的顺序出现,但我仍然会得到如下的混合响应:
https://test.com/test?4
https://test.com/test?7
https://test.com/test?1
https://test.com/test?3
我不确定代码是否有问题,或者在这种情况下我完全误解了dispatch_group_t
的目的。
我一直在挖掘并看到来自AFNetworking的matt关于使用Operations&amp; amp;集成一个简单解决方案的评论。 AF的会议很快就会公开,但它已经超过2年了。
我试图在不使用嵌套请求或NSOperations
由于
答案 0 :(得分:0)
您可以尝试2种方法
信号量
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSLog(@"NUMBER: %ld",(long)test);
[manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
dispatch_semaphore_signal(semaphore);
NSLog(@"task: %@",task.currentRequest.URL.absoluteString);
} failure:^(NSURLSessionTask *operation, NSError *error) {
//NSLog(@"Error: %@", error);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
WaitUntillFinished
[operation waitUntilFinished];
您可以在以下链接中查看详细实施: https://github.com/AFNetworking/AFNetworking/issues/1804