我現在做得這個項目里面包含了第三方支付,在使用的時候會有部分界面是調用網頁來展示的,但是當我使用自帶的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;
}
```