Get the http response code from every UIWebView re

2019-03-30 02:56发布

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 ?

1条回答
仙女界的扛把子
2楼-- · 2019-03-30 03:03

I have implemented it using

NSURLProtocol

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

查看更多
登录 后发表回答