iOS 如何使用WebView加载Https类型的网页

我现在做得这个项目里面包含了第三方支付,在使用的时候会有部分界面是调用网页来展示的,但是当我使用自带的WebView来加载这些网页的时候,就出错了:NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) 当时还不知道,后面在Mac下的浏览器打开就说什么是私密链接,而且网址是以Https开头的,百度了下,我这才知道原来是SLL没有设置。所以在加载Https的需要先用NSURLConnection来访问站点,然后在验证身份的时候,将该站点设置为可信任站点,最后用WebView重新加载一次就好了!

不多说了,贴代码:


//首先你得声明协议

//然后 你得声明三个全局变量

NSURLRequest*_originRequest;

NSURLConnection*_urlConnection;

BOOL_authenticated;

//再在 你需要用WebView加载网页的地方初始化Request

_originRequest= [NSURLRequestrequestWithURL:[NSURLURLWithString:urlStr]];

[self.allWebViewloadRequest:_originRequest];

//最后就是实现协议函数了

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

{

NSLog(@"Did start loading: %@ auth:%d", [[requestURL]absoluteString],_authenticated);

if(!_authenticated) {

_authenticated=NO;

_urlConnection= [[NSURLConnectionalloc]initWithRequest:_originRequestdelegate:self];

[_urlConnectionstart];

returnNO;

}

returnYES;

}

-(void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error{

// 102 == WebKitErrorFrameLoadInterruptedByPolicyChange

NSLog(@"***********error:%@,errorcode=%d,errormessage:%@",error.domain,error.code,error.description);

if(!([error.domainisEqualToString:@"WebKitErrorDomain"] && error.code==102)) {

//当请求出错了会做什么事情

}

}

#pragmamark-NURLConnectiondelegate

-(void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge

{

NSLog(@"WebController Got auth challange via NSURLConnection");

if([challengepreviousFailureCount]==0)

{

_authenticated=YES;

NSURLCredential*credential=[NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust];

[challenge.senderuseCredential:credentialforAuthenticationChallenge:challenge];

}else

{

[[challengesender]cancelAuthenticationChallenge:challenge];

}

}

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response

{

NSLog(@"WebController received response via NSURLConnection");

// remake a webview call now that authentication has passed ok.

_authenticated=YES;

[self.allWebViewloadRequest:_originRequest];

// Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)

[_urlConnectioncancel];

}

// We use this method is to accept an untrusted site which unfortunately we need to do, as our PVM servers are self signed.

- (BOOL)connection:(NSURLConnection*)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace

{

return[protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust];

}

//最后还需要一个NSURLRequest(NSURLRequestWithIgnoreSSL)的扩展,.m文件中只需要一个函数就好了。

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host

{

returnYES;

}

```

你可能感兴趣的:(iOS 如何使用WebView加载Https类型的网页)