废话不多说直接上代码

//
// 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. 洛谷 P1876 开灯

    传送门 这道题凭什么是! 就因为它代码短?! 还是我太菜了... 第$i$盏灯的开关与否只由其约数个数决定,又有约数公式: 当$n=p_1^{a_1}p_2^{a_2}...p_n^{a_n}$时,约 ...

  2. 【LG4185】[USACO18JAN]MooTube

    [LG4185][USACO18JAN]MooTube 题面 洛谷 题解 先将所有操作和询问离线 然后按照边权从大到小将操作和询问排序 利用\(two\;pointers\),每次扫到一个询问,将边权 ...

  3. idea 从javadoc中复制内容出来

    打开 tool window就行了 经验:百度google不到的东西太多了,要学会自己想办法,至少也要把功能都试一遍吧, 而且像这种东西官方一般会给方法实现你的目的,只不过有时候是把功能迁移了或者整合 ...

  4. set get方法诡异的空指针异常

    发现原来是我的bean没有实例化 我的一直都是这么实例化的: UserEntity userEntity = null;难怪每次用不了set方法 原来是没有实例化 实例化之后就能正常使用了 UserE ...

  5. 一、初识 Django

    一.引子 Django最初设计用于具有快速开发需求的新闻类站点,目的是要实现简单快捷的网站开发! 从好的方面来看,Web 开发激动人心且富于创造性:从另一面来看,它却是份繁琐而令人生厌的工作.通过减少 ...

  6. HDU-6315:Naive Operations(线段树+思维)

    链接:HDU-6315:Naive Operations 题意: In a galaxy far, far away, there are two integer sequence a and b o ...

  7. Python字符串/元祖/列表/字典互转

    #-*- coding:UTF-8 -*- #author:RXS002 #1.字典 dict = {'name':'Zara','age':7,'class':'First'} #字典转换为字符串, ...

  8. 第一次作业(homework-01)成绩公布

    已收到博客名.github名的同学得分列表: 学号后三位 成绩(0-10) 215 8082 0132 5184 5027 7194 9.5157 7074 8195 6222 8158 6128 8 ...

  9. 作业 20181120-3 Beta发布

    此作业要求参见:https://edu.cnblogs.com/campus/nenu/2018fall/homework/2408 小组介绍 组长:付佳 组员:张俊余 李文涛 孙赛佳 田良 于洋 段 ...

  10. 个人第十一周PSP

    11.24 --11.30本周例行报告 1.PSP(personal software process )个人软件过程. 类型 任务 开始时间                结束时间 中断时间 实际用 ...