9

Our app has a lot of web views in it and I recently added a NSURLProtocol to interceptor some of the requests from them.

I've noticed that some of the web views are calling the +[NSURLPRotocol canInitWithRequest:] method multiple times with what appears to be exactly the same request. Sometimes 6 or 7 times. I'm trying to figure out why this might be occurring.

Does anyone have any experience with this? I've logged out the [NSURL absoluteString] and httpMethod values and they are the same for each request. I would expect that this method would only be called once for any given file or resource needed from a server, not multiple times. And it seems to vary per web page.

any ideas?

drekka
  • 20,957
  • 14
  • 79
  • 135

1 Answers1

5

I'm not expert, but AFAIK this is normal behavior. [NSURLPRotocol canInitWithRequest:] may be called multiple times for the same request. If you want to be notified just once per request, you should catch it in -startLoading method. I found this tutorial helpful to construct simple NSURLProtocol subclass which will do just that: http://www.raywenderlich.com/59982/nsurlprotocol-tutorial

jesse
  • 650
  • 5
  • 19
  • for some reason startLoading is called only after the issue described by drekka. even if i return YES startLoading called after all requests call on canInitWithRequest. Do you have any idea why? thanks! – ElizaS Mar 16 '16 at 15:42
  • The only tip I can give is this: Be sure you aren't starting a connection that has already been started—particularly if you're using NSURLConnection, where some allocation methods start the connection automatically. – dgatwood May 08 '16 at 02:11
  • Is there any documentation supporting this? I'm also seeing this behaviour on my machine but... somehow it's not reproducible on other machines.... – Pawel Klapuch Aug 01 '22 at 15:14