Случайное получение кода NSURLErrorDomain = -1206 с использованием Alamofire - PullRequest
0 голосов
/ 10 февраля 2019

Я случайно получаю следующую ошибку, когда выполняю общую операцию синхронизации с использованием библиотеки Alamofire :

загрузка завершается с ошибкой Ошибка Domain = NSURLErrorDomain Code = -1206«Серверу« XXX.XXX.com »требуется сертификат клиента».UserInfo = {NSLocalizedDescription = Серверу «XXX.XXX.com» требуется сертификат клиента., NSErrorFailingURLStringKey = https://XXX.XXX.com/XXX/XXX, NSErrorFailingURLKey = https://XXX.XXX.com/XXX/XXX, _NSURLErrorRelatedURLSessionTaskErrorKey = (r) TKT = TRUE_LRT_LRT_LRT_LRT_LRT_TF_LRT_TF_LRT_TRK_TRT_TRKT_TKTKTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT5. Кроме того.LocalDataTask. <5>, NSUnderlyingError = 0x6000014344e0 {Домен ошибки = kCFErrorDomainCFNetwork Code = -1206 "(ноль)" UserInfo = {NSErrorPeerAddressKey = {длина = 16, емкость = 16, байт = 0x100201bb200000000000000000000000000000000*

Вот мой код,

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 Utility

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
    )
}

}

Пожалуйста, поделитесь своим предложением, как решить эту проблему.

...