5

I need to check the response status code while loading any of the url in the webview fo. For now we can consider any of the web application I am loading inside the web view.So I need to track down every request withing that webview and check out the response code accordingly. For finding the response code, I need to use NSUrlConnection inside the uiwebview's delegate method "shouldStartLoadWithrequest". Some thing like this -

- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
        navigationType:(UIWebViewNavigationType)navigationType{
      NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
      if (conn == nil) {
         NSLog(@"cannot create connection");
      }
      return YES;
}

And NSURLConnectionDelegate as --

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"connection:didReceiveResponse");
    [self log:@"received response."];
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    int status = [httpResponse statusCode];
     NSLog(@"http status code: %d", status);
    if (status == 200) {
      NSLog(@"Response OK");
    }
    else {
       NSLog(@"Response is not OK");
    }
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
   NSLog(@"connection:didReceiveData");
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"connection:didFailWithError - %@", error);
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
   NSLog(@"connectionDidFinishLoading");
}

But in this process, there are 2 calls on the server. One for the UIWebview and other for the NSUrlConnection. I just need a single call to the server in which I would be able to find the status code. Can anybody please guide me in this ?

mobizen
  • 483
  • 8
  • 20
  • I don't think there will even be a response in the shouldStartLoadWithRequest method as it hasn't started yet. Can't you just use the webViewDidFinishLoad method? – Darren Nov 22 '14 at 10:17
  • Iam facing the same problem. I've read ton of stackoverflow responses but I came across tutotial from Ray and this should doable with just one call ... http://www.raywenderlich.com/59982/nsurlprotocol-tutorial – Skodik.o Feb 28 '16 at 08:45
  • @Skodik.o : Yes, I have implemented it using NSURLProtocol. It solves the problem. – mobizen Feb 29 '16 at 09:32

1 Answers1

0

I have implemented it using

NSURLProtocol

. For more details, you can check it here - NSURLProtocol

mobizen
  • 483
  • 8
  • 20