Moya/RxSwift/ObjectMapper/Alamofire开发
2024-08-29 13:02:36
废话不多说直接上代码
//
// MoyaNetWorking.swift
// GreenAir
//
// Created by BruceAlbert on 2017/9/18.
// Copyright © 2017年 Mars. All rights reserved.
// import UIKit
import Moya
//import Alamofire
import RxSwift
import SwiftyJSON
import ObjectMapper typealias SuccessClosure = (_ result: AnyObject) -> Void
typealias FailClosure = (_ errorMsg: String?) -> Void enum RequestCode: String {
case failError = "0"
case success = "1"
} class MoyaNetWorking: NSObject {
static let sharedInstance = MoyaNetWorking()
private override init(){} let requestProvider = RxMoyaProvider<RequestApi>() func getCurrentAddressWeather<T: Mappable>(target:RequestApi, type:T.Type, successClosure:@escaping SuccessClosure, failClosure: @escaping FailClosure) {
_ = requestProvider.request(target).subscribe{ event -> Void in
switch event {
case .next(let response):
print("\(response.data)")
let json = JSON.init(data: response.data, options: .allowFragments, error: nil)
let info = Mapper<WeatherModel>().map(JSONObject: json.dictionaryObject)
guard let data = info?.result else {
failClosure("数据为空")
return
}
successClosure(data)
case .error(let error):
print("网络请求失败...\(error)")
default: break
} }
} } public enum RequestApi {
case weather(city:String, province: String)
} extension RequestApi: TargetType {
/// The parameters to be encoded in the request.
public var baseURL: URL {
return NSURL(string: "http://apicloud.mob.com/")! as URL //天气接口BaseUrl
} public var path: String {
switch self {
case .weather(_, _):
return "v1/weather/query"
}
} public var method: Moya.Method {
switch self {
case .weather(_, _):
return .get
default :
return .post
}
} public var parameters: [String : Any]? {
switch self {
case let .weather(city, province):
return ["key":"202a3152f2222", "city":city, "province":province]
default:
return nil
}
} public var parameterEncoding : ParameterEncoding {
return URLEncoding.default
}
// 单元测试用
public var sampleData: Data {
return "{}".data(using: String.Encoding.utf8)!
} public var task: Task {
return .request
} public var validate: Bool{
return true
} }
swift 请求成功和失败 block
typealias SuccessClosure = (_ result: AnyObject) -> Void
typealias FailClosure = (_ errorMsg: String?) -> Void
请求状态码
enum RequestCode: String {
case failError = "0"
case success = "1"
}
实例和遵守协议
static let sharedInstance = MoyaNetWorking()
let requestProvider = RxMoyaProvider<RequestApi>()
请求数据方法+数据监听(Rxswift)
func getCurrentAddressWeather<T: Mappable>(target:RequestApi, type:T.Type, successClosure:@escaping SuccessClosure, failClosure: @escaping FailClosure) {
_ = requestProvider.request(target).subscribe{ event -> Void in //Rxswift的元素监听
switch event {
case .next(let response):
print("\(response.data)")
let json = JSON.init(data: response.data, options: .allowFragments, error: nil)
let info = Mapper<WeatherModel>().map(JSONObject: json.dictionaryObject)
guard let data = info?.result else {
failClosure("数据为空")
return
}
successClosure(data)
case .error(let error):
print("网络请求失败...\(error)")
default: break
} }
}
请求api,以枚举方式设置接口,使用swift开发过一段的都知道
public enum RequestApi {
case weather(city:String, province: String)
}
设置api扩展且,遵守TargetType协议,TargetType的所有成员必须实现
extension RequestApi: TargetType {
/// The parameters to be encoded in the request.
public var baseURL: URL {
return NSURL(string: "http://apicloud.mob.com/")! as URL //天气接口BaseUrl
} public var path: String {
switch self {
case .weather(_, _):
return "v1/weather/query"//按照api的path,
}
} public var method: Moya.Method {
switch self {
case .weather(_, _):
return .get
default :
return .post
}
} public var parameters: [String : Any]? {
switch self {
case let .weather(city, province):
return ["key":"202a3152f2222", "city":city, "province":province]
default:
return nil
}
} public var parameterEncoding : ParameterEncoding {
return URLEncoding.default
}
// 单元测试用
public var sampleData: Data {
return "{}".data(using: String.Encoding.utf8)!
} public var task: Task {
return .request
} public var validate: Bool{
return true
} }
WeatherModel类及其相关类
//
// WeatherModel.swift
// GreenAir
//
// Created by BruceAlbert on 2017/9/18.
// Copyright © 2017年 Mars. All rights reserved.
// import UIKit
import ObjectMapper
class WeatherModel : Mappable {
var msg : String?
var retCode : String?
var result : AnyObject?
required init?(map: Map) {
} func mapping(map: Map) {
msg <- map["msg"]
retCode <- map["retCode"]
result <- map["result"]
}
} class WeatherUintModel : Mappable{
var airCondition : String?
var city : String?
var coldIndex : String?
var updateTime : String?
var date : String?
var distrct : String?
var dressingIndex : String?
var exerciseIndex : String?
var humidity : String?
var pollutionIndex : String?
var province : String?
var sunrise : String?
var sunset : String?
var temperature : String?
var time : String?
var washIndex : String?
var weather : String?
var week : String?
var wind : String?
var future : Array<WeatherData>?
required init?(map: Map) {
} func mapping(map: Map) {
airCondition <- map["airCondition"]
city <- map["city"]
coldIndex <- map["coldIndex"]
updateTime <- map["updateTime"]
date <- map["date"]
distrct <- map["distrct"]
dressingIndex <- map["dressingIndex"]
exerciseIndex <- map["exerciseIndex"]
humidity <- map["humidity"]
pollutionIndex <- map["pollutionIndex"]
province <- map["province"]
sunrise <- map["sunrise"]
sunset <- map["sunset"]
temperature <- map["temperature"]
time <- map["time"]
washIndex <- map["washIndex"]
weather <- map["weather"]
week <- map["week"]
wind <- map["wind"]
future <- map["future"]
}
} class WeatherData : Mappable {
var date : String?
var dayTime : String?
var night : String?
var temperature : String?
var week : String?
var wind : String?
required init?(map: Map) {
} func mapping(map: Map) {
date <- map["date"]
dayTime <- map["dayTime"]
night <- map["night"]
temperature <- map["temperature"]
week <- map["week"]
wind <- map["wind"]
}
}
最新文章
- WPF 仪表盘 刻度盘 动态 加载中 开源
- sync_object not in (&#39;TBL_Territory&#39;)
- [Android Tips] 2. Disable recent apps dialog on long press home button
- SQLite存储类(数据类型)
- github 开源项目
- Swift学习笔记十一
- 从后端到页面:如何全方位监控 Ruby 应用?
- 免费素材:25套免费的 Web UI 设计的界面元素(转)
- WaterWave
- 如何使用 Zend Expressive 建立 NASA 图片库?
- C. Tourist Problem
- Executor以及线程池
- 46个Linux面试常见问题送给你
- 【Android Studio安装部署系列】十一、Android studio获取数字签名信息
- 使用apidoc生成项目文档
- requests库写接口测试框架初学习
- join的简单总结
- redis键值操作
- MTK framework系统默认设置
- 1257: [CQOI2007]余数之和