废话不多说直接上代码

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

Moya/RxSwift/ObjectMapper/Alamofire开发的更多相关文章

  1. Swift高仿iOS网易云音乐Moya+RxSwift+Kingfisher+MVC+MVVM

    效果 列文章目录 因为目录比较多,每次更新这里比较麻烦,所以推荐点击到主页,然后查看iOS Swift云音乐专栏. 目简介 这是一个使用Swift(还有OC版本)语言,从0开发一个iOS平台,接近企业 ...

  2. 基于Moya、RxSwift和ObjectMapper优雅实现REST API请求

    在Android开发中有非常强大的 Retrofit 请求,结合RxJava可以非常方便实现 RESTful API 网络请求.在 iOS开发中也有非常强大的网络请求库 Moya ,Moya是一个基于 ...

  3. RxSwift + Moya + ObjectMapper

    https://www.jianshu.com/p/173915b943af use_frameworks! target 'RXDemo' do pod 'RxSwift' pod 'RxCocoa ...

  4. Moya 与 RxSwift 使用

    如在OC中使用AFNetworking一般,Swift我们用Alamofire来做网络库.而Moya在Alamofire的基础上又封装了一层: 1.关于moya moya 官方说moya有以下特性-_ ...

  5. ReactiveX 学习笔记(17)使用 RxSwift + Alamofire 调用 REST API

    JSON : Placeholder JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站. ...

  6. iOS:iOS开发非常全的三方库、插件等等

    iOS开发非常全的三方库.插件等等 github排名:https://github.com/trending, github搜索:https://github.com/search. 此文章转自git ...

  7. iOS开发之资料收集

    github排名:https://github.com/trending, github搜索:https://github.com/search. 此文章转自github:https://github ...

  8. iOS开发 非常全的三方库、插件、大牛博客等等

    UI 下拉刷新 EGOTableViewPullRefresh- 最早的下拉刷新控件. SVPullToRefresh- 下拉刷新控件. MJRefresh- 仅需一行代码就可以为UITableVie ...

  9. iOS 第三方库、插件、知名博客总结

    iOS 第三方库.插件.知名博客总结 用到的组件 1.通过CocoaPods安装 项目名称 项目信息 AFNetworking 网络请求组件 FMDB 本地数据库组件 SDWebImage 多个缩略图 ...

随机推荐

  1. 修改表的字段顺序(mysql)

    ALTER TABLE 表名 CHANGE 字段名 字段名 int not null default 1 AFTER 它前面的字段;

  2. Jmeter接口测试(九)授权

    下面应该是jmeter的授权设置,但是由于本人目前对这块了解还不深,暂时写个标题,以后有时间再来补充,大家可以先看下一篇内容

  3. python接口自动化1-发送get请求 前言

    前言 requests模块,也就是老污龟,为啥叫它老污龟呢,因为这个官网上的logo就是这只污龟,接下来就是学习它了. 一.环境安装 1.用pip安装requests模块 >>pip in ...

  4. qs.js - 更好的处理url参数

    第一次接触 qs 这个库,是在使用axios时,用于给post方法编码,在使用过程中,接触到了一些不同的用法,写在这里分享一下. qs.parse qs.parse 方法可以把一段格式化的字符串转换为 ...

  5. TPO 02 - Early Cinema

    TPO 02 - Early Cinema NOTE: 主要意思(大概就是主谓宾)用粗体标出:重要的其它用斜体: []中的是大致意思,可能与原文有关也可能无关,但不会离题 目的为训练句子/段落总结能力 ...

  6. Elastic-Job 分布式调度平台

    概述 referred:http://elasticjob.io/docs/elastic-job-lite/00-overview Elastic-Job是一个分布式调度解决方案,由两个相互独立的子 ...

  7. NO.04--我的使用心得之使用vue绑定class名

    今天聊一聊这个话题,其实方式有很多种,我今天介绍几种我使用到的,各位看官耐心看: 一.用 变量形式 绑定单个 Class 名 在 vue 中绑定单个 class 名还好说,直接写就可以了 <te ...

  8. centos 6.5 双网卡 上网 virtualbox nat hostonly

    虚拟机两张网卡:分别调成NAT(eth0)和host only(eht1)模式. nat的网卡不用设置,host only网卡调为(vi /etc/sysconfig/network-scripts/ ...

  9. 1035 Password (20 分)(字符串)

    注意下单复数 #include<bits/stdc++.h> using namespace std; pair<string,string>pa; int main() { ...

  10. Fluent Python: memoryview

    关于Python的memoryview内置类,搜索国内网站相关博客后发现对其解释都很简单, 我觉得学习一个新的知识点一般都要弄清楚两点: 1, 什么时候使用?(也就是能解决什么问题) 2,如何使用? ...