废话不多说直接上代码
// // 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"] } }