在请求拦截器中重试,不重试失败的请求

时间:2020-06-15 04:41:47

标签: ios swift alamofire

我正在使用swift开发ios应用程序。我已经使用alamofire进行API集成,在我的应用中,我正在使用请求拦截器处理令牌过期。

我想实现的目标 重试失败的请求

问题是 重试无限调用的委托方法,刷新令牌API无限调用,不重试失败的请求

我的班级扩展了请求拦截器班级

//
//  OAuthHandler.swift
//  TeleMedicineProvider
//
//  Created by Ari Garasuthan on 11/06/20.
//  Copyright © 2020 deemsysinc. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON

class OAuthHandler:RequestInterceptor
{
    private typealias RefreshCompletion = (_ succeeded:Bool,_ accessToken:String)->Void
    let defaults = UserDefaults.standard
    let teleconfig = TeleMedicineConfig()
    let endpoint = EndPoints()

    private var isRefreshing = false

    func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        guard urlRequest.url?.absoluteString.hasPrefix(TeleMedicineConfig.domainUrl) == true else
        {
            return completion(.success(urlRequest))
        }
        var urlRequest = urlRequest
        urlRequest.setValue(defaults.string(forKey: teleconfig.ACCESS_TOKEN), forHTTPHeaderField: "Authorization")
        completion(.success(urlRequest))
    }


    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
        guard let response = request.task?.response as? HTTPURLResponse,response.statusCode == 401 else {
            return completion(.doNotRetryWithError(error))
        }

            refreshToken{ [weak self] success,token in
                guard let self = self else {return}

                if(success)
                {
                    print("TheToken"+token)
                    self.defaults.set(token, forKey: "Bearer "+self.teleconfig.ACCESS_TOKEN)
                    completion(.retry)
                }
                else
                {
                    completion(.doNotRetry)
                }
            }

    }

    private func refreshToken(completion:@escaping RefreshCompletion) {
        let headers:HTTPHeaders = ["Content-Type": "application/x-www-form-urlencoded"]
        AF.request(endpoint.REFRESH_TOKEN,method: .post,parameters: ["refresh_token":self.defaults.string(forKey: self.teleconfig.REFRESH_TOKEN)!],encoding: URLEncoding.default,headers: headers).validate().responseJSON{
            [weak self] responseData in
            let json = responseData.value as? [String:Any]
            let status = json!["status"] as? Bool
            if(status == true)
            {
                let accessToken = json!["accessToken"] as? String
                completion(true,accessToken!)
            }
            else
            {
                completion(false,"")
            }
        }
    }


}

我的API请求单例类:

class AFWrapper:NSObject
{

   static let sharedDataWrapper = AFWrapper()

let defaults  = UserDefaults.standard

let teleconfig = TeleMedicineConfig()


var sessionManager:Session!

override init() {
    let configuration = URLSessionConfiguration.default
    sessionManager = Session(configuration:configuration,interceptor: OAuthHandler())
}

   func requestGET(url:String,headers:HTTPHeaders,completion:@escaping(JSON)->Void)
{
    sessionManager.request(url, method: .get
        , parameters: nil, encoding:URLEncoding.default, headers: headers).validate().response{
            (responseData) in
            guard let data = responseData.data else {
                print("Error")
                return
            }
            do{
                let JsonResponse = try JSON(data:data)
                completion(JsonResponse)
            }catch(let parsingError)
            {
                print(parsingError)
            }
    }
}

0 个答案:

没有答案