I searched/googled a lot but could not get the answer on how to capture HTTP response headers in UIWebview
. Say I redirect to user to registration gateway(which is already active) in UIWebview on App Launch and when user finishes the registration, the app should be notified with the successful unique id assigned to the user on registration which is passed back in HTTP Response Headers.
Is there any direct way to capture/print the HTTP Response headers using UIWebview
?
If you want a more high level API code of what @Richard J. Ross III's wrote, you need to subclass NSURLProtocol.
An
NSURLProtocol
is an object which handles URL Requests. So you can use it for specific tasks which are described better on NSHipster and Ray Wenderlich, which includes your case of getting the HTTP Headers from the Response.Code
Create a new class subclassing from NSURLProtocol and your .h file should look like this:
Your .m file should have these methods to handle what you wish for
Also last thing to do is to register this protocol to the loading system which is easy achievable on AppDelegate:
I love the objective-c runtime. Is there something that you want to do but don't have an API for it? DM;HR.
Alright, on a more serious note, here's the solution to this. It will capture every URL Response that initiated from
CFNetwork
, which is what UIWebView happens to use behind the scenes. It will also capture AJAX requests, image loads, and more.Adding a filter to this should probably be as easy as doing a regex on the contents of the headers.
There is no way to get the response object from the
UIWebView
(file a bug with apple for that, id say)BUT two workarounds
1) via the shared NSURLCache
if this works for you this is ideal
ELSE
UIWebView
:)that'd be a bad workaround for this! (as Richard pointed out in the comments.) It DOES have major drawbacks and you have to see if it is a valid solution in your case
NSHTTPURLResponse
has method likeFor more info https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/Reference/Reference.html#//apple_ref/occ/cl/NSHTTPURLResponse
EDIT: Sorry I did not think about
UIWebView
. My solution works if you useNSURLConnection
But if you feed you webview with a
NSURLConnection
then you have the chance to capture the connection including response headers.