How to connect to self signed servers using Alamofire 1.3

前端 未结 5 1071
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 10:52

I get the below error while connecting to self signed server.

Error Domain=NSURLErrorDomain Code=-1202 \"The certificate for this server is invalid. You might be co

5条回答
  •  悲哀的现实
    2020-12-08 11:24

    Another approach for my project. The ServerTrustPolicyManager is an open class, and it's serverTrustPolicy function is open too. So it can be override.

    // 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
    
            // or, if `host` contains substring, return `disableEvaluation`
            // Ex: host contains `my_company.com`, then trust it.
        }
    }
    

    Then,

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

    UPDATE @2018,01

    In order to trigger the ServerTrustPolicyManager, the project's Info.plist needs to be configured. I found the solution, detail at this post, cnoon's comment @ 1 Nov 2015.

    For example, if there are urls named site1.foo.com, site2.foo.com, .... Then add App Transport Security Settings -> Exception Domains -> foo.com dictionary, with following entries.

    • NSExceptionRequiresForwardSecrecy : NO
    • NSExceptionAllowsInsecureHTTPLoads : YES
    • NSIncludesSubdomains : YES

    More detail you can refer the post.

提交回复
热议问题