网上应该有很多相关的解决办法,这种是调用官方的API, 所以从http直接转https会容易点,而且要修改的地方不多,只需实现以下几个代理方法就可以了,把返回的NSData类型数据 encoding 一下,然后 loadHTMLString 就行了,不多说,直接上代码先:
@interface ViewController () <UIWebViewDelegate,NSURLConnectionDelegate,NSURLConnectionDataDelegate> {
UIWebView *webView;
NSURLConnection *connenction;
NSMutableData *mutableData;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
webView.delegate = self;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
[webView loadRequest:request];
[self.view addSubview:webView];
mutableData = [NSMutableData data];
}
// 相关代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([request.URL.scheme isEqualToString:@"https"]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
connenction = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connenction start];
#pragma clang diagnostic pop
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
// 判断是否是信任服务器证书
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
// 创建一个凭据对象
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
// 告诉服务器客户端信任证书
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
} else {
if ([challenge previousFailureCount] == 0) {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
} else {
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"response %@",response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[mutableData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *html = [[NSString alloc] initWithData:[mutableData copy] encoding:NSUTF8StringEncoding];
[webView loadHTMLString:html baseURL:[[NSURL alloc] init]];
[connenction cancel];
[mutableData setData:[NSData data]];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// 清空数据
[mutableData setData:[NSData data]];
}
以上方法亲测可行,而且如果你在用http请求时通过 bridgeWebview 实现了JS交互,也是可以的,不会有任何影响,只需在你之前的 UIWebviewController 中实现上面的几个代理方法 就可以了,这样既兼容了 http 请求 也可以兼容 https 请求。