Created
April 12, 2017 21:53
-
-
Save bfernandesbfs/e629a51916a57bfc95d712cd5febd78c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fileprivate class SessionDelegate: NSObject, URLSessionDelegate { | |
// MARK: - NSURLSessionDelegate | |
public func urlSession(_ session: URLSession, | |
didReceive challenge: URLAuthenticationChallenge, | |
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) | |
-> Void) { | |
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust && | |
Constants.selfSignedHosts.contains(challenge.protectionSpace.host) { | |
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) | |
completionHandler(.useCredential, credential) | |
} else { | |
completionHandler(.performDefaultHandling, nil) | |
} | |
} | |
struct Constants { | |
// A list of hosts you allow self-signed certificates on. | |
// You'd likely have your dev/test servers here. | |
// Please don't put your production server here! | |
static let selfSignedHosts: Set<String> = [] | |
} | |
} | |
extension URLSession { | |
static var sessionDefault: URLSession { | |
return URLSession( | |
configuration: URLSessionConfiguration.sessionConfiguration(), | |
delegate: SessionDelegate(), | |
delegateQueue: OperationQueue.main) | |
} | |
} | |
fileprivate extension URLSessionConfiguration { | |
fileprivate class func sessionConfiguration() -> URLSessionConfiguration { | |
let config = ephemeral | |
config.timeoutIntervalForRequest = 20 // Make things timeout quickly. | |
config.httpShouldUsePipelining = true // Might speed things up if your server supports it. | |
return config | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment