I want to package AFNetworking in order to that urls can request one by one , but o don't know how to package it. for example , there are three url request want to send to server , I hope that send one url request by AFNetworking first , and when the first one has finished , then send next one to server, and so on 。 I think it may need NSOperationQueue to do this job, but I don't know how to implementation it. Is anyone has write code like this? could you give me the .h and .m file to me ,so that I can modeling writing or use direct ,thanks a lot.
Asked
Active
Viewed 237 times
1 Answers
1
You probably want something like this if you are sending data like images or whatnot. If you are just sending simple requests then just use the defacto AFNetworking GET/POST instead of multipartFormRequestWithMethod
.
In short, create an operation for each request and add each one to an array. Then use batchOfRequestOperations
to perform each one. (From the docs).
NSMutableArray *mutableOperations = [NSMutableArray array];
for (NSURL *fileURL in filesToUpload) {
NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[mutableOperations addObject:operation];
}
NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
NSLog(@"All operations in batch complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

Gordonium
- 3,389
- 23
- 39
-
Thank you very much , the method is what I need, but I also want to give a limiting condition to the queue , that is when the first url request return successful data then send the next url request , otherwise, if return data with failure , stop the queue ,don't send the next url request. Then there will be a view on the screen , which has a button to retry sending the failure url request again ,if this url request return successful data then send the next url request ,and so on . can the limiting condition been implemented with the queue? and whether using mainQueue will pause UI? – kai Nov 17 '15 at 14:51
-
Sure. There are a number of ways that you could do that. The crudest would just be to perform the next request in the success block of the one before. If any of them fail then enable the retry button. Any UI that you want to do (such as enabling the retry button in the failure block) just run in on the main thread using `dispatch_async(dispatch_get_main_queue(), ^{ // code here });` – Gordonium Nov 17 '15 at 15:05