!!!使用前了解下Moya的基础用法
1、导入库
pod 'Moya/RxSwift'
pod 'HandyJSON', '~>5.0.2'
2、为Response和ObservableType追加扩展为了做模型映射
extension ObservableType where E == Response {
public func mappingModel<T: HandyJSON>(_ type: T.Type) -> Observable<T> {
return flatMap({ (response) -> Observable<T> in
return Observable.just(response.mappingModel(T.self))
})
}
}
extension Response {
func mappingModel<T: HandyJSON>(_ type: T.Type) -> T {
// 没有数据返回
if data.count < 1 {
if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "{}"){
return emptyValue
} else if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "[{}]"){
return emptyValue
}
}
// 获取请求response的data转成json
let jsonString = String.init(data: data, encoding: .utf8)
if let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) {
return model
}
return JSONDeserializer<T>.deserializeFrom(json: "{\"status\":\"request error\"}")!
}
}
3、使用方法 TestAPI为enum遵守了TargetType协议
MoyaProvider<TestAPI>()
.rx
.request(.reciptRequset)
.asObservable()
.mappingModel(RecipeBannerResponse.self)
.subscribe(onNext: { [weak self] (model) in
//self?.mModel.accept(model.data?.first ?? RecipeDataModel())
print("model: \(String(describing: model.data?.first))")
}, onError: {(error) in
print("error: \(error)")
})
.disposed(by: bag)