Search code examples
iphonecocoa-touchuiwebviewnsurlprotocol

How do you change the content-type of a custom NSURLProtocol?


I've written a custom subclass of NSURLProtocol, however it seems that whenever I use the protocol to load a request in UIWebView it assumes the data is content-type "text/html". Is there a way to specify that this content is actually something else (For instance "text/plain" or "image/png")?


Solution

  • The content-type is actually carried by NSURLResponse, which you can modify by using the NSURLProtocolClient method URLProtocol:didReceiveResponse:cacheStoragePolicy: for instance, to set to text/plain

    NSURLResponse *textResponse = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:@"text/plain" expectedContentLength:100 textEncodingName:@"UTF-8"];
    [self.client URLProtocol:self didReceiveResponse:textResponse cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];