UIWebView capturing the response headers

ACP picture ACP · Mar 18, 2013 · Viewed 14.6k times · Source

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?

Answer

Daij-Djan picture Daij-Djan · Mar 18, 2013

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

- (void)viewDidAppear:(BOOL)animated {
    NSURL *u = [NSURL URLWithString:@"http://www.google.de"];
    NSURLRequest *r = [NSURLRequest requestWithURL:u];
    [self.webView loadRequest:r];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSCachedURLResponse *resp = [[NSURLCache sharedURLCache] cachedResponseForRequest:webView.request];
    NSLog(@"%@",[(NSHTTPURLResponse*)resp.response allHeaderFields]);
}
@end

if this works for you this is ideal


ELSE

  1. you could use NSURLConnection altogether and then just use the NSData you downloaded to feed the 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

NSURL *u = [NSURL URLWithString:@"http://www.google.de"];
NSURLRequest *r = [NSURLRequest requestWithURL:u];
[NSURLConnection sendAsynchronousRequest:r queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *resp, NSData *d, NSError *e) {
    [self.webView loadData:d MIMEType:nil textEncodingName:nil baseURL:u];
    NSLog(@"%@", [(NSHTTPURLResponse*)resp allHeaderFields]);
}];