博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Moya/RxSwift/ObjectMapper/Alamofire开发
阅读量:4922 次
发布时间:2019-06-11

本文共 7286 字,大约阅读时间需要 24 分钟。

废话不多说直接上代码

////  MoyaNetWorking.swift//  GreenAir////  Created by BruceAlbert on 2017/9/18.//  Copyright © 2017年 Mars. All rights reserved.//import UIKitimport Moya//import Alamofireimport RxSwiftimport SwiftyJSONimport ObjectMappertypealias SuccessClosure = (_ result: AnyObject) -> Voidtypealias FailClosure = (_ errorMsg: String?) -> Voidenum RequestCode: String {    case failError = "0"    case success = "1"}class MoyaNetWorking: NSObject {    static let sharedInstance = MoyaNetWorking()    private override init(){}        let requestProvider = RxMoyaProvider
() func getCurrentAddressWeather
(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
().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) -> Voidtypealias FailClosure = (_ errorMsg: String?) -> Void

 请求状态码

enum RequestCode: String {    case failError = "0"    case success = "1"}

 实例和遵守协议

static let sharedInstance = MoyaNetWorking()let requestProvider = RxMoyaProvider
()

 请求数据方法+数据监听(Rxswift)

func getCurrentAddressWeather
(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
().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 UIKitimport ObjectMapperclass 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
? 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"] }}

 

转载于:https://www.cnblogs.com/fshmjl/p/7544291.html

你可能感兴趣的文章
[UE4]Button
查看>>
spi接口
查看>>
Hibernate学习笔记_关系映射
查看>>
enter键跨浏览器提交表单
查看>>
postgres开启慢查询日志
查看>>
HASHtable创建
查看>>
协议与非正式协议
查看>>
安装jdk+tomcat
查看>>
Python 多进程
查看>>
.ctor,.cctor 以及 对象的构造过程
查看>>
WordPress用户注册无法发送密码邮件怎么回事?
查看>>
Texture(ASDK)、ComponentKit、LayoutKit、YogaKit
查看>>
Linux常用指令
查看>>
python 修改文件名1.0
查看>>
UWP:使用Composition实现类似安卓的水波纹Ripple效果
查看>>
Unable to convert MySQL date/time value to System.DateTime 错误的处理
查看>>
56度烟台社区
查看>>
Dockerfile命令整理
查看>>
BZOJ.4572.[SCOI2016]围棋(轮廓线DP)
查看>>
Mac笔记
查看>>