如何处理一个处理程序中的所有types的请求的响应,而且还独特地处理Alamofire和Moya的每个请求
在我的应用程序中,我使用Moya和Alamofire (以及Moya / RxSwift和Moya-ObjectMapper )库来处理所有networking请求和响应。
我想处理一个处理程序中的所有types的请求的响应,但也唯一处理每个请求。
例如对于任何请求我可以得到响应“无效的版本”,我想避免检查每个响应,如果这个错误到达。
有没有一种优雅的方式来处理与Moya
这个用例?
显然,这是非常简单的,你应该创build自己的插件。 并将其添加到您的提供程序实例(您可以将其添加到init函数中)
例如:
struct NetworkErrorsPlugin: PluginType { /// Called immediately before a request is sent over the network (or stubbed). func willSendRequest(request: RequestType, target: TargetType) { } /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler. func didReceiveResponse(result: Result<Moya.Response, Moya.Error>, target: TargetType) { let responseJSON: AnyObject if let response = result.value { do { responseJSON = try response.mapJSON() if let response = Mapper<GeneralServerResponse>().map(responseJSON) { switch response.status { case .Failure(let cause): if cause == "Not valid Version" { print("Version Error") } default: break } } } catch { print("Falure to prase json response") } } else { print("Network Error = \(result.error)") } } }
我build议使用通用参数化方法。
class DefaultNetworkPerformer { private var provider: RxMoyaProvider<GitHubApi> = RxMoyaProvider<GitHubApi>() func performRequest<T:Mappable>(_ request: GitHubApi) -> Observable<T> { return provider.request(request).mapObject(T.self) } }
DefaultNetworkPerformer
将处理您的所有请求Moya TargetType
。 在我的情况下,这是GitHubApi
。 这个实现的例子是:
var networkPerformer = DefaultNetworkPerformer() let observable: Observable<User> = networkPerformer.performRequest(GitHubApi.user(username: "testUser"))
在这里你通知networking执行者,响应将包含User
对象。
observable.subscribe { event in switch event { case .next(let user): //if mapping will succeed here you'll get an Mapped Object. In my case it was User that conforms to Mappable protocol break case .error(let error): //here you'll get MoyaError if something went wrong break case .completed: break } }