Moya/RxSwift/ObjectMapper/Alamofire开发
废话不多说直接上代码
//
// 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开发的更多相关文章
- Swift高仿iOS网易云音乐Moya+RxSwift+Kingfisher+MVC+MVVM
效果 列文章目录 因为目录比较多,每次更新这里比较麻烦,所以推荐点击到主页,然后查看iOS Swift云音乐专栏. 目简介 这是一个使用Swift(还有OC版本)语言,从0开发一个iOS平台,接近企业 ...
- 基于Moya、RxSwift和ObjectMapper优雅实现REST API请求
在Android开发中有非常强大的 Retrofit 请求,结合RxJava可以非常方便实现 RESTful API 网络请求.在 iOS开发中也有非常强大的网络请求库 Moya ,Moya是一个基于 ...
- RxSwift + Moya + ObjectMapper
https://www.jianshu.com/p/173915b943af use_frameworks! target 'RXDemo' do pod 'RxSwift' pod 'RxCocoa ...
- Moya 与 RxSwift 使用
如在OC中使用AFNetworking一般,Swift我们用Alamofire来做网络库.而Moya在Alamofire的基础上又封装了一层: 1.关于moya moya 官方说moya有以下特性-_ ...
- ReactiveX 学习笔记(17)使用 RxSwift + Alamofire 调用 REST API
JSON : Placeholder JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站. ...
- iOS:iOS开发非常全的三方库、插件等等
iOS开发非常全的三方库.插件等等 github排名:https://github.com/trending, github搜索:https://github.com/search. 此文章转自git ...
- iOS开发之资料收集
github排名:https://github.com/trending, github搜索:https://github.com/search. 此文章转自github:https://github ...
- iOS开发 非常全的三方库、插件、大牛博客等等
UI 下拉刷新 EGOTableViewPullRefresh- 最早的下拉刷新控件. SVPullToRefresh- 下拉刷新控件. MJRefresh- 仅需一行代码就可以为UITableVie ...
- iOS 第三方库、插件、知名博客总结
iOS 第三方库.插件.知名博客总结 用到的组件 1.通过CocoaPods安装 项目名称 项目信息 AFNetworking 网络请求组件 FMDB 本地数据库组件 SDWebImage 多个缩略图 ...
随机推荐
- 20155323 第四次实验 Android程序设计实验报告
20155323 第四次实验 Android程序设计实验报告 实验内容 1.基于Android Studio开发简单的Android应用并部署测试; 2.了解Android.组件.布局管理器的使用: ...
- 北京Uber优步司机奖励政策(4月18日)
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...
- 【NOIP2018pj】题解
[NOIP2018pj]题解 \(T1\) 题面 洛谷 题解 好像并没有什么好说的... #include <iostream> #include <cstdio> #incl ...
- CF 1065 E. Side Transmutations
E. Side Transmutations http://codeforces.com/contest/1065/problem/E 题意: 长度为n的字符串,字符集为A,问多少不同的字符串.两个字 ...
- LVS入门篇(一)之ARP协议
1.概念 地址解析协议,即ARP(AddressResolutionProtocol),是根据IP地址获取物理MAC地址的一个TCP/IP协议.主机发送信息时将包含目标IP地址的ARP请求广播到网络上 ...
- HttpClient使用详解 (一)
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- activeX 打包
原文 http://www.docin.com/p-409284488.html CAB打包文档说明 文档目的 本文档的目的在于说明将ocx和dll以及相关的文件打包成一个CAB包,以便在网页下调用o ...
- ZT-----用javascrip写一个区块链
几乎每个人都听说过像比特币和以太币这样的加密货币,但是只有极少数人懂得隐藏在它们背后的技术.在这篇博客中,我将会用JavaScript来创建一个简单的区块链来演示它们的内部究竟是如何工作的.我将会称之 ...
- Spark配置参数的三种方式
1.Spark 属性Spark应用程序的运行是通过外部参数来控制的,参数的设置正确与否,好与坏会直接影响应用程序的性能,也就影响我们整个集群的性能.参数控制有以下方式:(1)直接设置在SparkCon ...
- Python操作摄像头
实践环境: 操作系统:Windows 7(X64) Python版本:python-2.7.13.msi 使用插件:pygame-1.9.1.win32-py2.7.msi 软件下载: python- ...