Correlate NSURLRequest with UIWebView

858 Views Asked by At

In iOS, I'd like to be able to associate an NSURLRequest--any NSURLRequest, whether a navigation request or image or stylesheet request--with the UIWebView that sent it. This seems to call for the implementation of an NSURLProtocol subclass to capture and analyze requests as they come through. However, I can't find a way to correlate a request with its web view, and NSURLProtocol only seems to understand NSURLRequests.

This would be fine for navigation requests, as I could make the association in my UIWebViewDelegate. But this won't work for secondary resource requests such as images, which do not trigger UIWebViewDelegate methods.

Anyone have any thoughts as to the best way to make this association?

2

There are 2 best solutions below

1
On

If I understand your question correctly, you could just do NSURL *url = [[webView request] URL];

0
On

In your custom protocol, canUseProtocol delegate method gets called for referenced resources as well. You may be able to leverage this hook to link your requests, but I am not sure if you can get a failure callback without cancelling that request and performing a separate one with the url.

Your question about referenced resources led me to that discovery, which allowed me to solve a caching problem i was having.

Thank you and I hope this helps in return!