1

I have a method which is called, and the first thing it does is ascertain when the network is reachable. If it's not, I'd like to wait 10s, then run the same method with the arguments/params that were initially passed in..

This is my disastrous attempt (I'm more a JS dev, relatively new to Objective-C):

- (void)sendRequestToURL:(NSString *)url withPostData:(NSString *)postData withPage:(int)page sortBy:(NSString *)sort completionBlock:(void (^)(NSDictionary *))completion {

    if(![FooNetworkManager isReachable]){
        self.lastRequest = ??? // lastRequest is an NSDictionary
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 10);
        dispatch_after(delay, dispatch_get_main_queue(), ^(void){
            [self sendRequestToURL:self.lastRequest]; // this is almost definitely wrong
        });
    }

}

In JavaScript, inside a method we have access to the arguments object that contains all the params that were passed into the method, not sure how to replicate this in Objective-C.

Also, self.lastRequest is defined further up in this same class:

@property(nonatomic, strong) NSDictionary *lastRequest;
benhowdle89
  • 36,900
  • 69
  • 202
  • 331

1 Answers1

6

In its simplest form you can dispense with lastRequest and do:

- (void)sendRequestToURL:(NSString *)url withPostData:(NSString *)postData withPage:(int)page sortBy:(NSString *)sort completionBlock:(void (^)(NSDictionary *))completion {

    if(![FooNetworkManager isReachable]){
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 10);
        dispatch_after(delay, dispatch_get_main_queue(), ^(void){
            [self sendRequestToURL:url withPostData:postData withPage:page sortBy:sort completionBlock:completion];
        });
    }
}

in this way you're simply capturing the passed parameters in the block. So you need to be careful that capturing mutable objects, if you have any, is acceptable...

You should also have some way to cancel the retry, or perhaps a maximum number of attempts, or even an exponential back off time in between attempts.

Wain
  • 118,658
  • 15
  • 128
  • 151