美文网首页
Swift Moya自定义插件---拦截Response并处理

Swift Moya自定义插件---拦截Response并处理

作者: ZYiDa | 来源:发表于2021-09-14 14:38 被阅读0次

在获取接口数据时,我们可能会遇到对特殊响应状态码进行统一处理的情况。在Moya中我们可以通过实现PluginType的一些方法来实现这个功能,如下:

//MARK: - 针对token验证失效处理的插件
/// 对response提前进行拦截处理
/// 然后根据业务需求进行成功回调或者失败回调
class TokenAuthorizationPlugin: PluginType {
    
    func process(_ result: Result<Response, MoyaError>, target: TargetType) -> Result<Response, MoyaError> {
        if let response = try? result.get(),
           let responseCode =  response.mapData(BasePluginModel.self).code{
            if responseCode == "401" {
                NotificationCenter.default.post(
                    name: AuthorizationTokenName,
                    object: nil
                )
                let obj = ["code": responseCode, "desc": "Token has expired,\n you will need to log in again","data":nil] as [String : Any?]
                let data = try! JSONSerialization.data(
                    withJSONObject: obj,
                    options: JSONSerialization.WritingOptions.fragmentsAllowed
                )
                let nResponse = Response(
                    statusCode: response.statusCode,
                    data: data,
                    request: response.request,
                    response: response.response
                )
                let error = MoyaError.jsonMapping(nResponse)
                return Result<Response, MoyaError>.failure(error);
            }
        }
        return result
    }
}

使用

public let APIServer = MoyaProvider<APIManager>(requestClosure: requestTimeoutClosure,plugins: [TokenAuthorizationPlugin()])

题外话:
通过自定义PluginType,我们可以实现很多统一处理的功能,比如:

  • HUDshowdismiss
  • Request进行发送前的包装处理,更优雅的设置header超时时间这些
    等等...

相关文章

网友评论

      本文标题:Swift Moya自定义插件---拦截Response并处理

      本文链接:https://www.haomeiwen.com/subject/bhiiwltx.html