Mac OS X Reference Library Apple Developer
Search

Handling Redirects and Other Request Changes

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 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

Did this document help you? Yes It's good, but... Not helpful...