Pergunta

I can't figure out a way of downloading objects in a queue using AFNetworking 2.0.

I have an array of ID's. I want to make a request with the last object from array, when this request is completed, make a second request, third request, and so on.. But if at least one request fails, I need to stop.

while ([dataArray count] > 0) {

    [[APIClient sharedClient] POST:@"/api/my_object.json" parameters:@{@"obj":[dataArray lastObject]} success:^(NSURLSessionDataTask *task, id responseObject) {
        [dataArray removeLastObject];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        break;
    }];
}

I Know this is not right, because i get async callbacks. So Maybe anyone could suggest of how to achieve this? Maybe using queues or something like that?

Thanks in advance for any help!

Foi útil?

Solução

Your solution is to make one request at the time. That means, start a new request only when you get a result from the last one.

Something like this:

-(void) makeNextRequest {
   __typeof__ (self) __weak weakSelf = self;
   [[APIClient sharedClient] POST:@"/api/my_object.json" parameters:@{@"obj":[dataArray lastObject]} success:^(NSURLSessionDataTask *task, id responseObject) {
        [dataArray removeLastObject];
        [weakSelf makeNextRequest];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top