0

所以我试图在每次请求之前检查承载是否有效,但是当我运行刷新令牌请求时,Alamofire 在调度前提条件下得到一个异常:我做错了什么?这甚至可能吗?

extension Session: SessionStateProvider {
    func request(for task: URLSessionTask) -> Request? {
        dispatchPrecondition(condition: .onQueue(rootQueue))

        return requestTaskMap[task]
    }

首先检查令牌的请求的主要调用者


private static func createRequest(urlConvertible:  URLRequestConvertible)-> Alamofire.DataRequest?{
        if let manager = sessionManager{
            return manager.request(urlConvertible)
///custom manager that checks the tokens
        }else if let manager = authenticatedManager{
            manager.verifyRequest(url: urlConvertible) { (result) in
                return result
            }

        }
        return nil
    }

    ///  This method make a request using the JSONAPI's Format - Only to the 'data' structure
    ///
    /// - Parameter urlConvertible: Codabel Onject to parse teh response
    /// - Returns: The Codable object if success or not
    static func requestJSONAPI<T: Codable> (_ urlConvertible: URLRequestConvertible) -> Observable<T> {
        initManager(urlConvertible: urlConvertible)

        //Create an RxSwift observable, which will be the one to call the request when subscribed to
        return Observable<T>.create { observer in
            let request = createRequest(urlConvertible: urlConvertible)?
                .debugLog()
                .validate()
                .responseCodableJSONAPI(keyPath: "data", completionHandler: { (response: AFDataResponse<T>) in
                    switch response.result {
                    case .success(let value):

                        let jsonDataString = String(data: response.data ?? Data(), encoding: String.Encoding.utf8)!
                        print("Post Request Params : \(jsonDataString)")
                        observer.onNext(value)

这是我的代码,其中 auth.refreshtokens 使用 AF.request 获取新令牌

    private func shouldRefreshToken() -> Bool {

        do {
            let jwt = try decode(jwt: accessToken)
            return jwt.expired
        } catch {

        }
        return false
    }

    func verifyRequest(url: URLRequestConvertible, completion: @escaping (_ result: DataRequest) -> Void){

        if  shouldRefreshToken() {
            let auth = interceptor
///makes an AF.request to get the new tokens - where it crashes
            auth.refreshTokens { [weak self] succeeded, accessToken, refreshToken in
                self?.accessToken = accessToken!
                completion((self?.sessionManager?.request(url))!)
            }
        }else{
            completion((self.sessionManager?.request(url))!)
        }

    }
´´´





4

1 回答 1

0

这可能是一个 Alamofire 错误。您能否在我们的 GitHub 上创建一个新问题,其中包含崩溃的完整堆栈跟踪以及您在此处发布的代码片段或示例项目?

此外,您的大部分异步处理都无法正常工作,例如您尝试return resultinside verifyRequest,但我不确定这是否与此问题有关。

此外,我建议将您的令牌处理重构为一个RequestInterceptor添加令牌的适配器和一个重试器,该重试器将在必要时重试请求时刷新令牌。不需要手动检查,Alamofire 自动支持这种事情。

于 2020-04-01T16:31:28.513 回答