网络层iOS 干货整理iOS开发资料收集区

ios 自签证书,webview加载https

2017-03-03  本文已影响63人  低头敲代码的小猿

首先如果你的证书是自签的,那么你的webview是是不是不能加载https的网址。如果是,且出现了如下的问题。那么就请接着看下去.

解决这个问题的办法,代码如下:

BOOL _Authenticated;

NSURLRequest * _FailedRequest; (两个全局变量)

- (void)createWebView {

_webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];

_webview.delegate = self;

[self.view addSubview:_webview];

NSString * string = [NSString stringWithFormat:@"%@%@",baseRequest, self.urlString];

NSURL * url = [NSURL URLWithString:string];

_FailedRequest = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.f];

[_webview loadRequest:_FailedRequest];

}

#pragma UIWebViewDelegate

- (void)webViewDidStartLoad:(UIWebView *)webView {

NSLog(@"webview开始加载!");

}

- (void)webViewDidFinishLoad:(UIWebView *)webView {

NSLog(@"webview加载完成!");

}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request  navigationType:(UIWebViewNavigationType)navigationType {

BOOL result = _Authenticated;

if (!_Authenticated) {

_FailedRequest = request;

NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

[urlConnection start];

}

return result;

}

#pragma NSURLConnectionDelegate

-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

NSString * string = [NSString stringWithFormat:@"%@%@",baseRequest, self.urlString];

NSURL* baseURL = [NSURL URLWithString:string];

if ([challenge.protectionSpace.host isEqualToString:baseURL.host]) {

[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

}

}

[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)pResponse {

_Authenticated = YES;

[connection cancel];

[_webview loadRequest:_FailedRequest];

}。

到这里,运行你的demo试试吧,奇迹会发生!

以上是参考了alstonwei在github上的一个demo的,demo的链接是https://github.com/alstonwei/UIWebView-HTTPS-Test。

上一篇 下一篇

猜你喜欢

热点阅读