在获取接口数据时,我们可能会遇到对特殊响应状态码进行统一处理的情况。在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
,我们可以实现很多统一处理的功能,比如:
-
HUD
的show
和dismiss
- 对
Request
进行发送前的包装处理,更优雅的设置header
超时时间这些
等等...
网友评论