美文网首页我爱编程
iOS UIWebview https 自签证书验证以及URL缓

iOS UIWebview https 自签证书验证以及URL缓

作者: 爱闹的凡 | 来源:发表于2018-04-16 14:04 被阅读116次

一、NSURLRequest各种缓存方式讲解

1.NSURLRequestUseProtocolCachePolicy NSURLRequest 默认的cache policy,使用Protocol协议定义。
2.NSURLRequestReloadIgnoringCacheData 忽略缓存直接从原始地址下载。
3.NSURLRequestReturnCacheDataDontLoad 只使用cache数据,如果不存在cache,请求失败;用于没有建立网络连接离线模式
4.NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data时才从原始地址下载。
5.NSURLRequestReloadIgnoringLocalAndRemoteCacheData 忽略本地和远程的缓存数据,直接从原始地址下载,与NSURLRequestReloadIgnoringCacheData类似。
6.NSURLRequestReloadRevalidatingCacheData :验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据

二、选择上面的忽略缓存模式可以解决部分问题,但还是存在部分js或者css改变,webview页面不能同步更新需要清除cookie

如果用AF的话
_requestW.HTTPShouldHandleCookies = NO;

或者

NSHTTPCookie *cookie;              
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];              
for (cookie in [storage cookies]) {  
       [storage deleteCookie:cookie];             
} 

三、webview https 用自签证书需要一下操作,正规证书不需要,遵守 UIWebViewDelegate,NSURLConnectionDelegate协议

@property (nonatomic) SSLAuthenticate authenticated;

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    PPLog(@"开始加载: %@ 授权:%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{
    PPLog(@"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{
    PPLog(@"WebController 已经收到响应并通过了 NSURLConnection请求");
    
    _authenticated = kTryAuthenticate;
    [_webView loadRequest:_requestW];
    [_urlConnection cancel];
}

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

相关文章

网友评论

    本文标题:iOS UIWebview https 自签证书验证以及URL缓

    本文链接:https://www.haomeiwen.com/subject/neuskftx.html