How to connect to self signed servers using Alamofire 1.3

前端 未结 5 1072
隐瞒了意图╮
隐瞒了意图╮ 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:47

    There is a way to change the Server Trust Policy of the Alamofire manager shared instance, but it's not recommended. Instead you should create your own customised instance of the manager. Here is the recommended solution, code is Swift 2.0 with Alamofire from swift-2.0 branch, compiled in Xcode7 beta 5.

    Creating customised instance of the manager

    Because you will not use the request method on the Alamofire, but use the one on your custom manager instead, you need to think of where to store the manager. What I do is to store it as static in my networking wrapper (the class that utilizes Alamofire and deals with my application networking needs). I set it up like this:

    private static var Manager : Alamofire.Manager = {
            // Create the server trust policies
            let serverTrustPolicies: [String: ServerTrustPolicy] = [
                "maskeddomain.com": .DisableEvaluation
            ]
            // Create custom manager
            let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
            configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
            let man = Alamofire.Manager(
                configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
                serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
            )
            return man
        }()
    

    Next step is to switch all your calls that use Alamofire.request() with Manager.request(), so you should have something like this:

    Manager.request(.GET, "http://stackoverflow.com").responseJSON(
        completionHandler: { (_, respose, result) -> Void in
                if result.isSuccess {
                    // enjoy your success
                } else if result.isFailure {
                    // deal with your failure
                }
        })
    

    If you want to change the shared instance of the manager anyway, go here for more info.

提交回复
热议问题