使用RxSwift和URLSession处理401状态

时间:2019-09-26 15:24:41

标签: swift rx-swift urlsession rx-cocoa

我目前有一个如下所示的网络客户端:

class Client<R: ResourceType> {

    let engine: ClientEngineType
    var session: URLSession

    init(engine: ClientEngineType = ClientEngine()) {
        self.engine = engine
        self.session = URLSession.shared
    }

    func request<T: Codable>(_ resource: R) -> Single<T> {
        let request = URLRequest(resource: resource)

        return Single<T>.create { [weak self] single in
            guard let self = self else { return Disposables.create() }
            let response = self.session.rx.response(request: request)

            return response.subscribe(
                onNext: { response, data in

                    if let error = self.error(from: response) {
                        single(.error(error))
                        return
                    }

                    do {
                        let decoder = JSONDecoder()
                        let value = try decoder.decode(T.self, from: data)
                        single(.success(value))
                    } catch let error {
                        single(.error(error))
                    }
            },
                onError: { error in
                    single(.error(error))
            })
        }
    }

    struct StatusCodeError: LocalizedError {
        let code: Int

        var errorDescription: String? {
            return "An error occurred communicating with the server. Please try again."
        }
    }

    private func error(from response: URLResponse?) -> Error? {
        guard let response = response as? HTTPURLResponse else { return nil }

        let statusCode = response.statusCode

        if 200..<300 ~= statusCode {
            return nil
        } else {
            return StatusCodeError(code: statusCode)
        }
    }
}

然后我可以调用类似的东西

let client = Client<MyRoutes>()
client.request(.companyProps(params: ["collections": "settings"]))
    .map { props -> CompanyModel in return props }
    .subscribe(onSuccess: { props in
      // do something with props
    }) { error in
        print(error.localizedDescription)
}.disposed(by: disposeBag)

我想开始处理401响应并刷新令牌并重试请求。

我正在努力寻找一种实现此目的的好方法。

我发现this excellent gist概述了实现此目标的方法,但是我正在努力在当前的客户中实现这一目标。

任何提示或指示,将不胜感激。

1 个答案:

答案 0 :(得分:1)

那是我的要旨! (感谢您将它称为出色的。)您是否看到其中附带的文章? https://medium.com/@danielt1263/retrying-a-network-request-despite-having-an-invalid-token-b8b89340d29

处理401重试有两个关键要素。首先,您需要一种将令牌插入请求并使用Observable.deferred { tokenAcquisitionService.token.take(1) }启动请求管道的方法。就您而言,这意味着您需要一个URLRequest.init,它将接受一个资源和一个令牌,而不仅仅是一个资源。

第二种方法是在收到401时抛出TokenAcquisitionError.unauthorized错误,并以.retryWhen { $0.renewToken(with: tokenAcquisitionService) }结束请求管道

因此,鉴于以上所述,为了处理令牌重试,您需要做的就是将我的TokenAcquisitionService带入您的项目并使用以下方法:

func getToken(_ oldToken: Token) -> Observable<(response: HTTPURLResponse, data: Data)> {
    fatalError("this function needs to be able to request a new token from the server. It has access to the old token if it needs that to request the new one.")
}

func extractToken(_ data: Data) -> Token {
    fatalError("This function needs to be able to extract the new token using the data returned from the previous function.")
}

let tokenAcquisitionService = TokenAcquisitionService<Token>(initialToken: Token(), getToken: getToken, extractToken: extractToken)

final class Client<R> where R: ResourceType {
    let session: URLSession

    init(session: URLSession = URLSession.shared) {
        self.session = session
    }

    func request<T>(_ resource: R) -> Single<T> where T: Decodable {
        return Observable.deferred { tokenAcquisitionService.token.take(1) }
            .map { token in URLRequest(resource: resource, token: token) }
            .flatMapLatest { [session] request in session.rx.response(request: request) }
            .do(onNext: { response, _ in
                if response.statusCode == 401 {
                    throw TokenAcquisitionError.unauthorized
                }
            })
            .map { (_, data) -> T in
                return try JSONDecoder().decode(T.self, from: data)
        }
        .retryWhen { $0.renewToken(with: tokenAcquisitionService) }
        .asSingle()
    }
}

请注意,在某些情况下,getToken函数可能必须提供一个要求用户凭据的视图控制器。这意味着您需要提供您的登录视图控制器(或UIAlertController)来收集数据。或者,也许您在登录时从服务器获得授权令牌和刷新令牌。在那种情况下,TokenAcquisitionService应该同时保留它们两个(即,其T应该是(token: String, refresh: String)。两者都可以。

该服务的唯一问题是,如果获取新令牌失败,则整个服务都将关闭。我还没有解决。