ios - WKWebView https 证书无效

标签 ios uiwebview ios8 certificate wkwebview

这是我用来允许证书的代码:

@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/

相关文章:

ios - 使用 Ghost Localizable.strings, "real"一个被忽略

uiwebview - 在加载之前找到 UIWebview 的内容高度

iOS8 Swift - TableView - Controller 不符合协议(protocol) UITableViewDataSource

ios - 如何使用 Swift 在 UICollection View 单元格中添加 TableView ?

ios - 新创建的 NSManagedObject 即使在保存后也会返回临时 objectID

iphone - 如何旋转 CGRect 或 CGImageCreateWithImageInRect?

ios - 我可以通过标签从 iOS 获取元素吗?

html - UIWebView 中带有 HTML 和 CSS 的 iPhone native 应用程序

iphone - uiwebview 不会滚动到底部

ios - UITableViewCell animateWithDuration 不起作用