I\'m using Xcode 7, Swift 2, and iOS9. I want to connect to a web service using NSURLSession but I get the following error when I try to connect:
2015-10-13
Take a look at this article.Shipping an App With App Transport Security particularly the sections about self-signed certificates.
You'll most likely need the delegate method of the form,
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
completionHandler(
.UseCredential,
NSURLCredential(trust: challenge.protectionSpace.serverTrust!)
)
}
Adding this to my own comms class that uses NSURLSession fixed the issue.
open your info.plist as a source code Add following:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
This should help.
For SWIFT 4:
func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(
.useCredential,
URLCredential(trust: challenge.protectionSpace.serverTrust!)
)
}
I received the error "The certificate for this server is invalid. You might be connecting to a server that is pretending to be "www.yoururl.com" which could put your confidential information at risk."
I solved this by having doing this in my httpclient file. The following code will ignore the authentication request completely.
var session: URLSession?
session = URLSession(configuration: sessionConfiguration(), delegate: self, delegateQueue: nil)
private func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition) -> Void) {
completionHandler(
.cancelAuthenticationChallenge
)
}
Also not sure if it impacted the above but In my info.plist I had "Allow Transport Security Settings" & the child key-value option "Allow Arbitrary Loads" which I set to YES.
When creating the URL Session, use the initializer, that sets the delegate along with the configuration, like below:
let urlSession = URLSession(configuration: urlSessionConfiguration, delegate: self, delegateQueue: nil)
Then, implement the following delegate method, it should work.
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, urlCredential)
}
However, it is very important to note, that this is a security issue, and we should not be trying to connect to servers with invalid certificates.