NSURLConnection sendAsynchronousRequest with Resend Function

I have my main UI thread that calls the sendAsynchronousRequest method to retrieve data.

 [NSURLConnection sendAsynchronousRequest:[self request] queue:[NSOperationQueue alloc] init completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) { if (error) { //error handler } else { //dispatch_asych to main thread to process data. } }]; 

All this is beautiful and good.

My question is here, I need to implement the retry function on error.

  • Can I do this in this block and call sendSynchronousRequest to try again since this is a background queue.
  • Or send the main thread and try the main thread again (by calling sendAsynchronousRequest and repeating the same loop).
+4
source share
1 answer

You get the request by calling [self request] . If request is atomic @property or otherwise thread safe, I can't think of any reason why you could not try again from a non-main thread.

Alternatively, you can put a copy of the request in a local variable before your call +sendAsynchronousRequest:queue: If you do this, then call it in the completion handler, it will be saved implicitly and [self request] will be called only once.

Generally speaking, this is probably not a very good model. If the service is disabled, there are no other checks, it will just try forever. You can try something like this:

 NSURLRequest* req = [self request]; NSOperationQueue* queue = [[NSOperationQueue alloc] init]; __block NSUInteger tries = 0; typedef void (^CompletionBlock)(NSURLResponse *, NSData *, NSError *); __block CompletionBlock completionHandler = nil; // Block to start the request dispatch_block_t enqueueBlock = ^{ [NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:completionHandler]; }; completionHandler = ^(NSURLResponse *resp, NSData *data, NSError *error) { tries++; if (error) { if (tries < 3) { enqueueBlock(); } else { // give up } } else { //dispatch_asych to main thread to process data. } }; // Start the first request enqueueBlock(); 
+1
source

All Articles