Created
November 26, 2011 01:48
-
-
Save stuntgoat/1394818 to your computer and use it in GitHub Desktop.
NSURLConnection Delegate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// inside MyHTTPRequest.m | |
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response { | |
/* This delegate method is called before the connection sends a NSURLRequest. | |
(NSURLResponse *)response will be nil when this method is not called by the delegate recieving a redirect | |
(NSURLRequest *)request will contain the NSURLRequest object that (NSURLConnection *)connection is about | |
to send to the server. | |
For example, during an initial request to a server, this delegate method is called | |
and (NSURLResponse *)response will be nil, since the delegate has not received a HTTP | |
redirect ( the delegate has not received any response from the server yet because no request | |
has been sent yet ) | |
*/ | |
if (response != nil) { // response contains a HTTP redirect ( ie. status code 302) | |
// request will now contain the redirected URL. Our original request data has been lost! | |
// if the request is the same as the URL for the initial request, recreate | |
// the original request, including the HTTP method, HTTPBody, and HTTPHeaderFields | |
if ([[requestURL absoluteString] isEqualToString:[[request URL] absoluteString]]) { | |
NSMutableURLRequest *newRequest = [[NSMutableURLRequest alloc] initWithURL:requestURL]; | |
[newRequest setHTTPMethod:requestMethod]; | |
if (requestBodyData != nil) { | |
[newRequest setHTTPBody:requestBodyData]; | |
} | |
[newRequest setAllHTTPHeaderFields:[request allHTTPHeaderFields]]; | |
return [newRequest autorelease]; | |
} else { | |
// request is not the same as our original request, so return the redirected request URL | |
return request; | |
} | |
} else { | |
// response == nil so send the original request | |
return request; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment