I am using NSURLConnection to send an HTTP request and running it with [[NSURLConnection alloc] initWithRequest:request delegate:self]; where "request" is a configured NSMutableURLRequest object. Upon an HTTP error based on error code (404 or 500), I want to retry the request.
I get the error response and HTTP status code in the "connection: didReceiveResponse" delegate methods. How should I implement the retry request?
Thanks in advance!
P.S: I tried canceling the connection and starting it on receiving an error but it has no effect as NSURLConnection releases the delegate after it finishes loading or is cancelled.
-----UPDATE-----
-(void)doHTTPGet:(NSString *)url delegate:(id <NSURLConnectionDelegate>)delegate timeout:(NSTimeInterval)timeout
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:timeout];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// send request by instanciating NSURLConnection
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:delegate];
}
In my model class, I have the caller method and delegates
Caller:
[MyModel doHTTPGet:url delegate:self timeout:HTTP_TIMEOUT];
Delegate Methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
httpResponseStatusCode = [httpResponse statusCode];
DLOG(@"HTTP status code=%ld", (long)httpResponseStatusCode);
if (httpResponseStatusCode == 404)
{
// RETRY HERE
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[httpResponseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// some code PROCESSING RESPONSE
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}