使用Alamofire随机获取NSURLErrorDomain代码= -1206

时间:2019-02-10 08:35:33

标签: swift authentication ssl-certificate alamofire

每当我使用 Alamofire 库执行整体同步操作时,我都会随机出现以下错误:

  

加载失败,错误为Error Domain = NSURLErrorDomain代码= -1206“   服务器“ XXX.XXX.com”需要客户端证书。”   UserInfo = {NSLocalizedDescription =服务器“ XXX.XXX.com”需要一个   客户证书。,   NSErrorFailingURLStringKey = https://XXX.XXX.com/XXX/XXX,   NSErrorFailingURLKey = https://XXX.XXX.com/XXX/XXX,   _NSURLErrorRelatedURLSessionTaskErrorKey =(       “ LocalDataTask。<5>”),_NSURLErrorFailingURLSessionTaskErrorKey = LocalDataTask。<5>,   NSUnderlyingError = 0x6000014344e0 {Error Domain = kCFErrorDomainCFNetwork   代码= -1206“(空)” UserInfo = {NSErrorPeerAddressKey = {长度= 16,容量= 16,字节=   0x100201bb2c80a7c80000000000000000}}}} [-1206]

这是我的代码,

SessionManager

static let sharedManager = APIManager()

let defaultManager: Alamofire.SessionManager

init() {

    let sessionConfiguration = URLSessionConfiguration.default
    sessionConfiguration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
    sessionConfiguration.httpCookieStorage = nil
    sessionConfiguration.requestCachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData

    let policies: [String: ServerTrustPolicy] = [SecureDomains.live.rawValue: .disableEvaluation]
    let policyManager = ServerTrustPolicyManager(policies: policies)

    self.defaultManager = Alamofire.SessionManager(configuration: sessionConfiguration, serverTrustPolicyManager: policyManager)

    self.defaultManager.delegate.sessionDidReceiveChallenge = { session, challenge in
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
            return (.useCredential, KeychainManager.credentialFromKeychain())
        } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            return (.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
        }
        return (.performDefaultHandling, .none)
    }

}

RequestURL

    func request(_ signature: Signature, responseOnMainQueue: Bool = true, completionHandler: @escaping ImporterCompletionHandler) {

    let headers = constructHeadersForSignature(signature)

    defaultManager.request(signature.urlString, method: signature.method, parameters: signature.parameters, encoding: signature.encoding, headers: headers)

        .responseJSONOnSelectedQueue(responseOnMainQueue: responseOnMainQueue) { response in

            if let confirmedStatusCode = response.response?.statusCode as Int?, !signature.isResponseExpected, response.data?.count == 0, confirmedStatusCode == StatusCode.statusSuccess.rawValue {
                completionHandler(response.request?.url?.absoluteString, nil, nil, nil)
                return
            }

            switch response.result {

            case .failure(let error):

                performBlockOnMainThread {

                    if let confirmedRequestURLString = response.request?.url?.absoluteString,
                        let confirmedResponse = response.response, response.response?.statusCode != NSURLErrorCancelled {

                        self.updateFailureInAnalytics(error: error, response: response, requestUrl: confirmedRequestURLString)

                    }

                }

            default:
                break
            }

            self.handleResponse(response, signature: signature, responseOnMainQueue: responseOnMainQueue, completionHandler: completionHandler)

    }

}

ResponseSerialization实用程序

public extension DataRequest {

@discardableResult
public func responseJSONOnSelectedQueue(
    queue: DispatchQueue? = nil,
    options: JSONSerialization.ReadingOptions = .allowFragments,
    responseOnMainQueue: Bool,
    completionHandler: @escaping (DataResponse<Any>) -> Void)
    -> Self {

    var queue: DispatchQueue?

    if !responseOnMainQueue {
        queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
    }

    return response(
        queue: queue,
        responseSerializer: DataRequest.jsonResponseSerializer(options: options),
        completionHandler: completionHandler
    )
}

}

请分享您的建议,如何解决这个问题。

0 个答案:

没有答案