代码简单 (解析数据使用ObjectMapper+SwiftyJSON)
首先写个遵循自Moya的TargetType协议的枚举
import Moya
import Result
import RxSwift
import ObjectMapper
import SwiftyJSON
import MBProgressHUD
fileprivate let lj_baseURL = "https://www.baidu.com"
enum LJApiManager {
case Login([String: Any])
case otherURL
}
extension LJApiManager: TargetType {
var baseURL: URL {
switch self {
case .Login:
return URL(string: lj_baseURL)!
default:
return URL(string: lj_baseURL)!
}
}
var path: String {
switch self {
case .Login:
return "login"
default:
return ""
}
}
var method: Moya.Method {
switch self {
case .Login:
return .post
default:
return .post
}
}
var sampleData: Data {
switch self {
case .Login:
return "".data(using: .utf8)!
default:
return "".data(using: .utf8)!
}
}
var task: Task {
switch self {
case .Login(let parameters):
return .requestParameters(parameters: parameters, encoding: URLEncoding.default)
default:
return .requestPlain
}
}
var headers: [String : String]? {
return nil
}
}
可选:Moya的插件PluginType
public final class LJRequestPlugin: PluginType {
// 请求开始
public func willSend(_ request: RequestType, target: TargetType) { UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
// 请求结束
public func didReceive(_ result: Result
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
解析数据给Observable写个扩展
extension Observable {
func mapObject
return self.map({ response in
guard let dict = response as? [String: Any], let object = Mapper().map(JSON: dict) else { throw LJNetError.JSONError
}
return object
})
}
func mapArray
return self.map { response in
let json = JSON(response)
guard let array = json["body"].arrayObject as? [[String: Any]] else {
throw LJNetError.JSONError
}
return Mapper().mapArray(JSONArray: array)
}
}
}
enum LJNetError: String {
case JSONError = "JSON解析错误"
case OtherError = "其他错误"
}
extension LJNetError: Swift.Error {}
定义一个全局的MoyaProvider
let provider = MoyaProvider
写个基本请求类 (UserModel是一个用户模型)
import Moya
import RxSwift
import ObjectMapper
final class LJBaseModel {
init() {
}
static var share: LJBaseModel {
struct Static {
static let instance: LJBaseModel = LJBaseModel()
}
return Static.instance
}
func login(_ paras: [String: Any]) -> Observable
return rx_provider.rx.request(.Login(paras)).filterSuccessfulStatusCodes().asObservable().mapJSON().mapObject(type: UserModel.self)
}
}
使用
LJBaseModel.share.login(["username": "admin", "password": "123456"]).subscribe(onNext: { userModel in
print(userModel.result.name)
}).disposed(by: disposeBag)