Get the http response code from every UIWebView request

烈酒焚心 提交于 2020-01-22 15:03:47

问题


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:


I have implemented it using

NSURLProtocol

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



来源:https://stackoverflow.com/questions/22607244/get-the-http-response-code-from-every-uiwebview-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!