pod 'Moya/RxSwift'
pod 'HandyJSON'
pod 'RxSwift'
pod 'RxCocoa'
pod 'NSObject+Rx'
NetworkHelper.swift
extension Array: HandyJSON {}
extension String: HandyJSON {}
extension Int: HandyJSON {}
extension Float: HandyJSON {}
extension Double: HandyJSON {}
extension Bool: HandyJSON {}
struct BaseResponseModel<T: HandyJSON>: HandyJSON {
var code: Int = 0
var message: String?
var data: T?
}
extension ObservableType where Element == Response {
func mapHandyObservable<T: HandyJSON>(type: T.Type) -> Observable<BaseResponseModel<T>> {
return self.flatMap { response -> Observable<BaseResponseModel<T>> in
if let model = response.mapHandyModel(T.self) {
if model.code == 401 {
let error = CommonError(code: 401, message: "Token invalid")
return Observable.error(error as Error)
}
return Observable.just(model)
}
let error = CommonError(code: -1, message: "Mapping model failure")
return Observable.error(error as Error)
}
}
}
extension Response {
func mapHandyModel<T>(_ type: T.Type) -> BaseResponseModel<T>? {
do {
let str = try self.mapString()
if let model = BaseResponseModel<T>.deserialize(from: str) {
return model
}
return nil
} catch let error {
MLog(error)
return nil
}
}
}
class CommonError: Error {
var code: Int = 0
var message: String? = nil
init(code: Int, message: String? = nil) {
self.code = code
self.message = message
}
}
使用
1、LoginApi.swift
enum LoginApi {
case login
}
extension LoginApi: TargetType {
var baseURL: URL {
return URL(string: "your base url")!
}
var path: String {
switch self {
case .login:
return "your api path"
}
}
var method: Moya.Method {
switch self {
case .login:
return .get
}
}
var task: Moya.Task {
switch self {
case .login:
return .requestPlain
}
}
var headers: [String : String]? {
return nil
}
}
2、LoginApiService.swift
class LoginApiService: NSObject {
static let shared = LoginApiService()
private let provider = MoyaProvider<LoginApi>()
func login() -> Single<BaseResponseModel<LoginModel>> {
provider.rx.request(LoginApi.login).asObservable().mapHandyObservable(type: LoginModel.self).asSingle()
}
}
3、LoginViewModel.swift
class LoginViewModel: NSObject {
func login() {
LoginApiService.shared.login().subscribe(onSuccess: { response in
// Do some thing
}, onFailure: { error in
// Do some thing
}).disposed(by: rx.disposeBag)
}
}