gpt4 book ai didi

swift - 这是专门使用 NSURLConnection 来处理可转换为 NSURLSession 的自签名证书吗?

转载 作者:搜寻专家 更新时间:2023-10-31 08:08:28 24 4
gpt4 key购买 nike

我在用于测试服务的 VM 中有一个自签名证书。使用在 UIWebView to view self signed websites (No private api, not NSURLConnection) - is it possible? 中找到的答案我能够编写可正常运行的 swift 2.0 代码。 Xcode 7 告诉我 NSURLConnection 已弃用,我应该改用 NSURLSession。我迁移此代码的尝试均未成功,并且其他答案中描述的常见转换方案似乎都不适用。

如果我创建一个新的 NSURLSession 以使用我的委托(delegate)方法处理身份验证挑战,其他负载仍然发生在 sharedSession 上,因此失败。

var authRequest : NSURLRequest? = nil
var authenticated = false
var trustedDomains = [:] // set up as necessary

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if !authenticated {
authRequest = request
let urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)!
urlConnection.start()
return false
}
else if isWebContent(request.URL!) { // write your method for this
return true
}
return processData(request) // write your method for this
}

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let challengeHost = challenge.protectionSpace.host
if let _ = trustedDomains[challengeHost] {
challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
}
}
challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
authenticated = true
connection.cancel()
webview!.loadRequest(authRequest!)
}

最佳答案

通过在第一种方法之前添加此行,我能够抑制弃用警告。我更喜欢一个替代 NSURLConnection 的解决方案,但在没有它的情况下,这将是必须的。

// hide NSURLConnection deprecation
@available(iOS, deprecated=9.0)

关于swift - 这是专门使用 NSURLConnection 来处理可转换为 NSURLSession 的自签名证书吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com