views:

30

answers:

1

Riddle me this: I am using a NSURLConnection on an iPhone Simulator SDK 3.1.2 object to issue multiple sequential (not concurrent) https requests. Everything works fine 95% of the time, but every so often (maybe around 50-100 requests) I get the situation where the delegate method

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

is called after [connection start], but without any call to the delegate method

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

I have reduced the problem down to the source below. From what I understand this breaks the contract of NSURLConnection's defined behaviour. Has anyone else had this problem, and is it a known bug or am I using NSURLConnection wrong?

static BOOL hasSeenResponse = NO;

    //Create a NSURLConnection and start it
-(void) begin {
    NSURL* url = [NSURL URLWithString@"https://some.domain.com/some/path/?some=query"];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyNever];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    if ([NSURLConnection canHandleRequest:request]) {
        NSURLConnection* connection = [[NSURLConnection connectionWithRequest:request delegate:self] retain];
        hasSeenResponse = NO;
        [connection start];
    }
}     

#pragma mark NSURLConnection Delegate Methods
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (!hasSeenResponse) {
        NSLog(@"\n\nNo Response Recieved\n");
    }
    [connection release];
    [self begin];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [connection release];
    [self begin];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    hasSeenResponse = YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
}
A: 

I was able to fix the problem by adding the delegate for re-directs which always accepts

-(NSURLRequest *)connection:(NSURLConnection *)connection
            willSendRequest:(NSURLRequest *)request
           redirectResponse:(NSURLResponse *)redirectResponse
{
    return request;
}

As I understand it, this is the default behavior so I do not know why this solves the problem.

The URL I was sending the request to, did issue a re-direct, but that also does not explain why the HTTP request worked the other ~95% of the time.

I hope this helps someone with a similar problem in the future.

Akusete