把今天遇到的問題以及網(wǎng)上查找的方法結(jié)合一下七蜘,解決UIWebView加載https網(wǎng)站報錯 “Error Domain=NSURLErrorDomain Code=-1202 ”的方法。
報錯原因:主要是因?yàn)闇y試環(huán)境的證書是自簽名的墙懂,所以存在這樣的問題橡卤,而為什么有的https地址不會報錯呢?這就要說到證書是否是通過CA證書中心發(fā)布的损搬,如果是則不會碧库,否則就會在第三次握手的時候不成功而報錯。
解決方案:
NSAppTransportSecurity中 把NSAllowsArbitraryLoads 設(shè)置為YES巧勤,并不能解決問題嵌灰。
//聲明3個變量
NSURLConnection *_urlConnection;
NSURLRequest *_request;
BOOL _authenticated;
//UIWebView代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *urlString = [NSString stringWithFormat:@"%@",request.URL];
//這里判斷url地址是哪個
if (!_authenticated && [urlString isEqualToString:@"************"]) {
DT(@"_authenticated ");
_authenticated =NO;
_urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_request = request;//request賦值
[_urlConnection start];
return NO;
}
return YES;
}
//NSURLConnectionDelegate 方法
#pragma mark - NURLConnection delegate
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
DT(@"didReceiveAuthenticationChallenge");
if ([challenge previousFailureCount] == 0)
{
_authenticated = YES;
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
} else
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
DT(@"didReceiveResponse");
// remake a webview call now that authentication has passed ok.
_authenticated = YES;
[self.webView loadRequest:_request]; // self.webView替換成自己的webview
// Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)
[_urlConnection cancel];
}
// 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
{
DT(@"canAuthenticateAgainstProtectionSpace");
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
希望這個解決方案對大家有用。