UIWebview.loadURL() 但 URL 是自签名证书。 Swift iOS

UIWebview.loadURL() but URL is a self-signed certificate. Swift iOS

我有一个URLhttps://203.xxx.xxx.xxx。此 URL 仅用于我们的 测试目的

我想在 Swift2.0 的 UIWebview 中加载这个 URL。可惜 !证书已过期。

我在 Android 中成功完成了同样的操作,但在 Swift 中遇到了问题。

请多指教......


我到现在都做了什么!!


01. Defined AppTransportSecurity in info.plist

    <key>NSAppTransportSecurity</key>
            <dict>
                <key>NSAllowsArbitraryLoads</key>
                <true/>
            </dict>
  1. 尝试使用连接(canAuthenticateAgainstProtectionSpace)和连接(willSendRequestForAuthenticationChallenge)

但是没有成功


当我在 Safari 中加载相同的 URL 时会发生什么??


错误说:Safari cannot verify the IDENTITY

需要绕过这个的帮助。


也尝试了一些链接:(这可能是解决方案)

@implementation NSURLRequest (NSURLRequestWithIgnoreSSL) 

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
    return YES;
}

@end

但是如何在 Swift 2.0 中实现呢? 如果我错了请在Swift.

中正确引导

终于得到答案:

第 1 步 >> import SafariServices

第 2 步 >> 将 NSURLConnectionDelegate 与您的 ViewController 一起使用,即

class ViewController:UIViewController, NSURLConnectionDelegate

步骤 3 >> 覆盖方法:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace?) -> Bool

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge)

第 4 步 >> 转到 viewDidLoad 在 Webview 中加载 URL 的位置,并进行更改:

let url = NSURL (string: URL)//where URL = https://203.xxx.xxx.xxx
let requestObj = NSURLRequest(URL: url!)
var request: NSURLRequest = NSURLRequest(URL: url!)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
YOUR_WEBVIEW.loadRequest(requestObj);

第 5 步 >> 使用 shouldStartLoadWithRequest 和 return 转到 webView。如果你 return 为假,你永远不会得到结果。

func webView(IciciWebView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool
{
//Do whatever you want to do.

 return true
}

第 6 步 >> 更新函数:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace?) -> Bool
    {
        print("In canAuthenticateAgainstProtectionSpace");

        return true;
    } 

第 7 步 >> 更新函数:

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) 
    {
        print("In willSendRequestForAuthenticationChallenge..");
        challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
        challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)

    }

参考:Swift 的开发人员参考、Whosebug 的大量页面和 Google 的一些论坛。

这些步骤解决了我的问题,现在我可以在网络视图中加载自签名 URL。