这是我用来允许证书的代码:
@interface NSURLRequest(DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
@end
@implementation NSURLRequest(DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
return [host isEqualToString:@"mysite.com"];
}
@end
然后我像那样初始化我的 WKWebView :
NSURL *urlReq = [NSURL URLWithString:@"mysite.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:urlReq];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[urlReq host]];
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
mainWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
[mainWebView setNavigationDelegate:self];
[mainWebView loadRequest:request];
它适用于 http 网站,但我在使用 https 时遇到此错误:
The certificate for this server is invalid. You might be connecting to a server that is pretending to be “mysite.com” which could put your confidential information at risk.
当我使用 UIWebView 并实现函数“canAuthenticateAgainstProtectionSpace”时,它是有效的,但现在我不明白我必须做什么。
我是不是遗漏了什么或者 WKWebView 无法处理 HTTPS?
最佳答案
试试这个,对我有用
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
NSLog(@"Allowing all");
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
CFDataRef exceptions = SecTrustCopyExceptions (serverTrust);
SecTrustSetExceptions (serverTrust, exceptions);
CFRelease (exceptions);
completionHandler (NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:serverTrust]);
}
不要忘记添加到 Info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
关于ios - WKWebView https 证书无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26510988/