iOS The certificate for this server is invalid.

今天将http改为https时,遇到了下面报错
image.png

需要我们自定义Session:
image.png

然后请求时,使用自定义Session替代AF:
image.png

关键代码如下:

private let networkShareInstance = NetworkTool()
//注意192.168.13.179需要改为自己的域名或IP
let serverTrustManager = ServerTrustManager(allHostsMustBeEvaluated: false,
                                                    evaluators: ["192.168.13.179": DisabledTrustEvaluator()])

var manage : Alamofire.Session!

class NetworkTool: NSObject {
    class var shareInstance: NetworkTool {
        return networkShareInstance
    }
    
    fileprivate override init() {

        super.init()

        manage = Session(serverTrustManager: serverTrustManager)
    }
}

extension NetworkTool {
    
    //get
    private func requestDatas(_ type: HTTPMethod, urlString: String, parameters: [String: Any]?, success: @escaping RequestSuccess, fail: @escaping ReqResponseFail) {
        
        let urlstr = BaseUrl + urlString
       
        //之前是AF,现在改为manage
        manage.request(urlstr, method: type, parameters: parameters, headers: headers(), interceptor: nil) { urlRequest in
            urlRequest.timeoutInterval = requestTimeoutInterval
        }.responseJSON { response in
            switch (response.result) {
            case .success(let data):
                success(data)
                break
            case .failure(let error):
                fail(error)
            }
        }
    }
}

extension NetworkTool {
    func headers() -> HTTPHeaders {
        var httpHeaders = HTTPHeaders()
        httpHeaders.add(name: "Content-Type", value: "application/json")
        
        let token: String = Defaults.token
        if token.count > 0 {
            httpHeaders.add(name: "Authorization", value: "Bearer " + token)
        }
        return httpHeaders
    }
}

你可能感兴趣的:(iOS The certificate for this server is invalid.)