lundi 9 novembre 2015

Multi part NSArray Post AFNetworking

I have a large NSArray I am wanting to split into chunks and send to my web server, upon completion of each chunk I then need to update the fields in my SQLite DB that relate to each item in each array chunk.

This is the code I am currently running, where I try to use a call back to receive success or failure then update my local SQLite DB where appropriate.

- (void)postlowData:(NSArray *)lowMArray Callback:(void (^)(NSError *error, BOOL success))callback;
{
// Currently this method is sending the whole lowMArray
// What I want to do is Split lowMArray into a chunkArray (where chunk is 20 of the leading items from lowMArray)
// I would then send chunkArray with the following code, when I receive a response I then want to update local SQLite DB with result and recall this method to start on the next 20 chunks.
        // Create Json data from lowMArray
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:lowMArray
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:nil];

        // Construct post request
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/lows", _silServerBaseUrl]]];
        request = [self applyAuth:request];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:jsonData];

        // Send post request
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
//                NSLog(@"Response Failed!");
                callback(error, NO);
            } else {
//                NSLog(@"Response Success!");
                callback(error, YES);
                // On success add itmes from lowChunkArray so that you can adjust sent_Flag later
            }
        }];
        [dataTask resume]; // runs task
}

The issue I am running into is that when I run this code if I am splitting the array into chunks sending the chunk adjusting the main array for the next chunk I don't get a confirmed callback till the very end of all the requests, at which point I have lost track of what success or failure?

Maybe I am going about this the wrong way, but If anyone could help me that would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire