我現(xiàn)在做得這個(gè)項(xiàng)目里面包含了第三方支付,在使用的時(shí)候會(huì)有部分界面是調(diào)用網(wǎng)頁來展示的,但是當(dāng)我使用自帶的WebView來加載這些網(wǎng)頁的時(shí)候锚赤,就出錯(cuò)了:NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) 當(dāng)時(shí)還不知道题翻,后面在Mac下的瀏覽器打開就說什么是私密鏈接,而且網(wǎng)址是以Https開頭的平夜,百度了下蝶棋,我這才知道原來是SLL沒有設(shè)置。所以在加載Https的需要先用NSURLConnection來訪問站點(diǎn)忽妒,然后在驗(yàn)證身份的時(shí)候玩裙,將該站點(diǎn)設(shè)置為可信任站點(diǎn),最后用WebView重新加載一次就好了段直!
不多說了吃溅,貼代碼:
//首先你得聲明協(xié)議
//然后 你得聲明三個(gè)全局變量
NSURLRequest*_originRequest;
NSURLConnection*_urlConnection;
BOOL_authenticated;
//再在 你需要用WebView加載網(wǎng)頁的地方初始化Request
_originRequest= [NSURLRequestrequestWithURL:[NSURLURLWithString:urlStr]];
[self.allWebViewloadRequest:_originRequest];
//最后就是實(shí)現(xiàn)協(xié)議函數(shù)了
- (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)) {
//當(dāng)請(qǐng)求出錯(cuò)了會(huì)做什么事情
}
}
#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];
}
//最后還需要一個(gè)NSURLRequest(NSURLRequestWithIgnoreSSL)的擴(kuò)展,.m文件中只需要一個(gè)函數(shù)就好了鸯檬。
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host
{
returnYES;
}
```