废话不多说直接上代码

//
// 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"]
}
}

最新文章

  1. WPF 仪表盘 刻度盘 动态 加载中 开源
  2. sync_object not in (&#39;TBL_Territory&#39;)
  3. [Android Tips] 2. Disable recent apps dialog on long press home button
  4. SQLite存储类(数据类型)
  5. github 开源项目
  6. Swift学习笔记十一
  7. 从后端到页面:如何全方位监控 Ruby 应用?
  8. 免费素材:25套免费的 Web UI 设计的界面元素(转)
  9. WaterWave
  10. 如何使用 Zend Expressive 建立 NASA 图片库?
  11. C. Tourist Problem
  12. Executor以及线程池
  13. 46个Linux面试常见问题送给你
  14. 【Android Studio安装部署系列】十一、Android studio获取数字签名信息
  15. 使用apidoc生成项目文档
  16. requests库写接口测试框架初学习
  17. join的简单总结
  18. redis键值操作
  19. MTK framework系统默认设置
  20. 1257: [CQOI2007]余数之和

热门文章

  1. slqite3练习
  2. 【BZOJ2395】[Balkan 2011]Timeismoney
  3. thinkphp5 开启多语言
  4. springboot入门之一:环境搭建(续)
  5. R Language Learn Notes
  6. javaweb(三十八)——事务
  7. python全栈开发-前方高能-内置函数2
  8. DruidDataSource源码分析
  9. sqoop导入数据到hive表中的相关操作
  10. php json 转换