iOS UIWebView 加載自簽名證書Https網頁

目前源碼已經上傳至Githup須要參考源碼的能夠點擊這裏:https://github.com/AustinKuture/UIWebViewSelfSignedHttps.gitgit

使用UIWebView 加載頁面時,咱們的經常使用方法大都是這樣的(或者使用WKWebView):github

UIWebView *webView = [UIWebView alloc]initWithFrame:CGRectMake(0,0,200,200);
[webView loadRequest:[NSURLRequest requestWithURL:url]];
[self.view addSubView:webView];

有時咱們也會用UIWe不View加載網頁時設置Cookie,在這裏咱們使用NSHTTPCookieStorage實現管理共享的cookie,並將存儲一個共享實例,這些Cookie在全部應用程序之間是共享的,而且是跨進程同步保存的,經過對Cookie設置可讓咱們像電腦瀏覽網頁同樣,靈活的對Cookie信息進行設置和清除,使應用端加載網頁信息時更加的方便,Cookie的設置與清除以下所示:web

//設置Cookie
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];  
[cookieProperties setObject:@"cookie_user" forKey:NSHTTPCookieName];  
[cookieProperties setObject:uid forKey:NSHTTPCookieValue];  
[cookieProperties setObject:@"xxx.xxx.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];  
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion]; 
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];  

NSHTTPCookie *cookieuser = [NSHTTPCookie cookieProperties];  
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieuser]; 

 NSURL *url = [NSURL URLWithString:url];   
 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];  
 [webView loadRequest:request];

//清除Cookie
- (void)deleteCookie{  
    NSHTTPCookie *cookie;  

    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];  

    NSArray *cookieAry = [cookieJar cookiesForURL: [NSURL URLWithString: url]];  

    for (cookie in cookieAry) {  

        [cookieJar deleteCookie: cookie];  

    }  
}

雖然UIWebView使用較爲靈活,幾乎與電腦端加載網頁同樣的方便,可是因爲種種緣由iOS的UIWebView在使用自簽名證書加載網頁時仍然不能正常的加載數據並顯示,對此咱們可使用NSURLConnection和UIWebView的代理方法,實現對自簽名證書在必定狀況下,自動在程序後臺進行驗證與自動信任,從而加載出咱們所想要顯示的網頁,具體使用步驟以下:微信

1,建立一個繼承自UIWebView的類AKWebView,在.h文件中添加兩個方法,一個是初始化類方法(單例),另外一個是WebView的實現方法:cookie

#import <UIKit/UIKit.h>

@interface AKWebView : UIWebView

+(instancetype)shareWebView;
- (void)webViewWithLoadRequestWithURL:(NSURL *)url Fram:(CGRect)fram;

@end

2,在.m文件中,首先添加咱們所要用到的代理協議,並建立屬性:佈局

#import "AKWebView.h"

@interface AKWebView ()<UIWebViewDelegate,NSURLConnectionDataDelegate>

@property (nonatomic,strong) NSURLConnection *urlConnection;
@property (nonatomic,strong) NSURLRequest *requestW;
@property (nonatomic) SSLAuthenticate authenticated;

@end

3,實現類初始化方法shareWebView:ui

@implementation AKWebView

+(instancetype)shareWebView{
    static dispatch_once_t onece = 0;
    static AKWebView *webView = nil;
    dispatch_once(&onece, ^(void){
        webView = [[self alloc]init];
    });
    return webView;
}

4,實現webView的實例化方法,在這裏主要是爲了配置WebVeiw的大小,佈局,添加代理,以及Request:atom

#pragma mark ***UIWebView 加載方法***
- (void)webViewWithLoadRequestWithURL:(NSURL *)url Fram:(CGRect)fram{
    
    self.frame = fram;
    self.delegate = self;
    _requestW = [NSURLRequest requestWithURL:url];
    [self loadRequest:_requestW];
}

5,實現各代理方法:url

#pragma mark ***UIWebView 代理方法***
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSLog(@"開始加載: %@ 受權:%d", [[request URL] absoluteString], _authenticated);
    
    if (!_authenticated) {
        _authenticated = kNeverAuthenticate;
        
        _urlConnection = [[NSURLConnection alloc] initWithRequest:_requestW delegate:self];
        
        [_urlConnection start];
        
        return NO;
    }
    
    return YES;
}


#pragma mark ***NURLConnection 代理方法***
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
    NSLog(@"WebController 已經獲得受權正在請求 NSURLConnection");
    
    if ([challenge previousFailureCount] == 0){
        _authenticated = kTryAuthenticate;
        
        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{
    NSLog(@"WebController 已經收到響應並經過了 NSURLConnection請求");
    
    _authenticated = kTryAuthenticate;
    [self loadRequest:_requestW];
    [_urlConnection cancel];
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{
    
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}




@end

6,使用方法,在使用時候先導入AKWebView的頭文件,在想要加載自簽名證書https網頁的控制器中,建立AKwebView並實現其方法,添加URL,及Fram大小便可:spa

AKWebView *webView = [AKWebView shareWebView];
[webView webViewWithLoadRequestWithURL:url Fram:CGRectMake(0, 0, 500, 500)];
[self.view addSubview:webView];

 

 

 

"既專一技術也享受生活--iOS資源庫"

QQ羣:524955567

 

天天一篇最有價值的文章

微信公衆號:YiKun_info

微信公衆號:

相關文章
相關標籤/搜索