1

根据先前的响应,我有一些请求需要一个一个触发。这很简单,NSOperation并试图找出 Sessions & 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 的评论,关于在 AF 中使用操作和会话集成一个简单的解决方案,它很快就会公开,但它是 2 年前的事了。

我试图在不使用嵌套请求或NSOperations

谢谢

4

1 回答 1

0

您可以尝试 2 种方法

  1. 信号

    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);
    
  2. 等到完成

    [operation waitUntilFinished];
    

您可以在以下链接查看详细实施: https ://github.com/AFNetworking/AFNetworking/issues/1804

于 2016-04-17T18:33:32.557 回答