????UIWebView在訪問(wèn)正常簽名的https網(wǎng)站是沒(méi)有問(wèn)題的行施,只是在訪問(wèn)自簽名https時(shí)發(fā)生錯(cuò)誤,無(wú)法正常展示頁(yè)面內(nèi)容蛾号。主要原因是證書認(rèn)證失敗。這里我們可以通過(guò)網(wǎng)絡(luò)請(qǐng)求轉(zhuǎn)發(fā)的方式來(lái)繞過(guò)證書認(rèn)證失敗的問(wèn)題展运。
? ? 以下是具體的代碼:
????增加幾個(gè)屬性保存
????@property (nonatomic, strong) NSURLRequest *originRequest;//原始網(wǎng)絡(luò)請(qǐng)求
????@property (nonatomic, strong) NSURLConnection *urlConnection;//轉(zhuǎn)換為urlConnection
????@property (nonatomic, assign) BOOL authenticated;//是否通過(guò)認(rèn)證
? ??- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
? ? NSString*absoluteUrl = [[request URL] absoluteString];
? ? NSLog(@"網(wǎng)頁(yè)地址為:%@",[request URL]);
? ? NSString*scheme = [[requestURL]scheme];
? ? if([scheme isEqualToString:@"https"]) {
? ? ? ? //如果是https:的話拗胜,那么就用NSURLConnection來(lái)重發(fā)請(qǐng)求怒允。從而在請(qǐng)求的過(guò)程當(dāng)中吧要請(qǐng)求的URL做信任處理。
? ? ? ? if (!_authenticated) {
? ? ? ? ? ? _authenticated=NO;
? ? ? ? ? ? self.originRequest =? request;
? ? ? ? ? ? _urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
? ? ? ? ? ? [_urlConnection start];
? ? ? ? ? ? returnNO;
? ? ? ? }
? ? }
? ? return YES;
}
然后在NURLConnection delegate中設(shè)置
- (void)connection:(NSURLConnection*)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge
{
? ? if([challenge previousFailureCount] ==0) {
? ? ? ? _authenticated = YES;
? ? ? ? //NSURLCredential 這個(gè)類是表示身份驗(yàn)證憑據(jù)不可變對(duì)象仰美。憑證的實(shí)際類型聲明的類的構(gòu)造函數(shù)來(lái)確定咖杂。
? ? ? ? NSURLCredential *cre = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
? ? ? ? [challenge.sender useCredential:cre forAuthenticationChallenge:challenge];
? ? }
? ? else
? ? {
? ? ? ? [challenge.sender 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.webView loadRequest:self.originRequest];
? ? // Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)
? ? [_urlConnection cancel];
}
? ? 在實(shí)際應(yīng)用中诉字,大家可以自定義一個(gè)UIWebView知纷,方便后續(xù)增加新的功能,比如js交互等等