Alamofire with a self-signed certificate / ServerTrustPolicy

前端 未结 4 1222
说谎
说谎 2020-12-03 05:13

I want to use Alamofire to communicate with my server over a https connection with a self signed certificate. My environment runs on localhost. I\'ve tried to connect, but t

4条回答
  •  眼角桃花
    2020-12-03 05:45

    My approach for self-signed https. The ServerTrustPolicyManager is an open class, and it's serverTrustPolicy function is open too. So it can be override.

    In my case, the server list will grow in future. If I hard-code the https list, I will need to maintain the list when adding new https server. So, I decide to override the ServerTrustPolicyManager class in order to meet my needs.

    // For Swift 3 and Alamofire 4.0
    open class MyServerTrustPolicyManager: ServerTrustPolicyManager {
    
        // Override this function in order to trust any self-signed https
        open override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
            return ServerTrustPolicy.disableEvaluation
        }
    }
    

    Then,

        let trustPolicies = MyServerTrustPolicyManager(policies: [:])
        let manager = Alamofire.SessionManager(configuration: sessionConfig, delegate: SessionDelegate(), serverTrustPolicyManager: trustPolicies)
    

提交回复
热议问题