Posiadam certyfikat z podpisem własnym w maszynie wirtualnej używanej do testowania mojej usługi. Używając odpowiedzi znalezionych w UIWebView to view self signed websites (No private api, not NSURLConnection) - is it possible? udało mi się napisać działający szybki kod 2.0. Xcode 7 mówi, że NSURLConnection
jest przestarzałe i powinienem zamiast tego użyć NSURLSession
. Żadna z moich prób migracji tego kodu nie powiodła się i nie ma zastosowania żaden ze zwykłych scenariuszy konwersji opisanych w innych odpowiedziach.Czy to wyspecjalizowane wykorzystanie NSURLConnection do obsługi autopodpisanych certyfikatów zamienionych na NSURLSession?
Jeśli utworzę nowy NSURLSession
, aby obsłużyć wyzwanie uwierzytelnienia za pomocą moich metod delegowania, pozostałe obciążenia nadal będą występować na sharedSession
, a zatem nie będą działać.
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!)
}