harshal jadhav harshal jadhav - 2 years ago 166
iOS Question

How to use Alamofires ServerTrustPolicy.disableEvaluation in swift 3

This is my session manager class

import UIKit
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
import Reqres


class Manager: SessionManager {
static let sharedInstance: Manager = Manager()
static let manager: Manager = {
let configuration = Reqres.defaultSessionConfiguration()
let manager = Manager(configuration: configuration)

return manager
}()

func getRequest(url:URL,param:Parameters,withSuccess success:@escaping (_ response: Dictionary<String, Any>) -> ()){
guard Utils.isInternetAvailable() else{
Utils.showAlert(message: "Internet connection lost", action: {

})
return
}
Utils.addHUD()
Alamofire.request(url, method: .get, parameters: param, encoding: URLEncoding.default).responseJSON { (response:
DataResponse<Any>) in
guard response.result.isSuccess else{
Utils.hideHUD()
Utils.showAlert(message: (response.result.error?.localizedDescription)!, action: {

})
return
}
Utils.hideHUD()
print(response.request!) // original URL request
print(response.response!) // HTTP URL response
print(response.data!) // server data
print(response.result) // result of response serialization
success(response.result.value! as! Dictionary<String, Any>)
}
}
}


I have to make request to a server url which is an https request without valid ssl certificates.I have applied server policies to do so but still getting the error:
"The certificate for this server is invalid"

other alternatives that i have tried

class Manager: SessionManager {
static let manager: Manager = {
let configuration = Reqres.defaultSessionConfiguration()
let serverTrustPolicies: [String: ServerTrustPolicy] = ["192.168.1.28:8443": .DisableEvaluation]
let manager = Manager(configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))

return manager
}()

Answer Source

Try this which seems to be working for me -

extension SessionManager {
static func getManager() -> SessionManager{

    let serverTrustPolicies: [String: ServerTrustPolicy] = [
        "192.168.1.28:8443": .disableEvaluation
    ]

    let configuration = Reqres.defaultSessionConfiguration()
    configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders

    return Alamofire.SessionManager(
        configuration: configuration,
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
}

}

And to use this SessionManager do the following -

var manager: SessionManager?
manager = SessionManager.getManager()
manager?.request// Here is your request call.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download