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
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.
Create a new class subclassing from NSURLProtocol and your .h file should look like this:
@interface CustomURLProtocol : NSURLProtocol
@property (nonatomic, strong) NSURLConnection *connection;
@end
Your .m file should have these methods to handle what you wish for
@implementation CustomURLProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
// Here you can add custom filters to init or not specific requests
return YES;
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
// Here you can modify your request
return request;
}
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {
return [super requestIsCacheEquivalent:a toRequest:b];
}
- (void)startLoading {
// Start request
self.connection = [NSURLConnection connectionWithRequest:self.request delegate:self];
}
- (void) stopLoading {
[self.connection cancel];
self.connection = nil;
}
#pragma mark - Delegation
#pragma mark NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
// Here we go with the headers
NSDictionary *allHeaderFields = [httpResponse allHeaderFields];
}
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.client URLProtocol:self didLoadData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self.client URLProtocolDidFinishLoading:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self.client URLProtocol:self didFailWithError:error];
}
Also last thing to do is to register this protocol to the loading system which is easy achievable on AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[NSURLProtocol registerClass:[CustomURLProtocol class]];
return YES;
}