A server may redirect a request for one URL to another URL. The delegates for NSURLConnection
and NSURLDownload
can be notified when this occurs for their connection.
To handle a redirect for an instance of NSURLConnection
, implement the connection:willSendRequest:redirectResponse:
delegate method (for NSURLDownload
, implement download:willSendRequest:redirectResponse:
). If the delegate implements this method, it can examine the new request and the response that caused the redirect, and respond in one of four ways:
The delegate can allow the redirect by simply returning the provided request.
The delegate can create a new request, pointing to a different URL, and return that request.
The delegate can reject the redirect and receive any existing data from the connection by returning nil
.
The delegate can cancel both the redirect and the connection by sending the cancel
message to the NSURLConnection or NSURLDownload.
The delegate also receives the connection:willSendRequest:redirectResponse:
message if the NSURLProtocol
subclass that handles the request has changed the NSURLRequest
in order to standardize its format, for example, changing a request for http://www.apple.com
to http://www.apple.com/
. This occurs because the standardized, or canonical, version of the request is used for cache management. In this special case, the response passed to the delegate is nil
and the delegate should simply return the provided request.
The example implementation in Listing 1 allows canonical changes and denies all server redirects.
Listing 1 Example of an implementation of connection:willSendRequest:redirectResponse:
-(NSURLRequest *)connection:(NSURLConnection *)connection |
willSendRequest:(NSURLRequest *)request |
redirectResponse:(NSURLResponse *)redirectResponse |
{ |
NSURLRequest *newRequest = request; |
if (redirectResponse) { |
newRequest = nil; |
} |
return newRequest; |
} |
If the delegate doesn't implement connection:willSendRequest:redirectResponse:
, all canonical changes and server redirects are allowed.
Last updated: 2010-03-24