swift 网络请求之解析模型
2018-07-31 本文已影响0人
yuezishenyou
一.基于 Alamofire 和 HandyJSON 框架,二次封装网络请求和网络检测。
a.网络检测文件
import UIKit
import Alamofire
class GBNetworkReachability: NSObject {
static let reachAbility = GBNetworkReachability();
var reachAble: Bool = {
var reach = true
let manager = NetworkReachabilityManager(host: "www.baidu.com")
let status = manager?.networkReachabilityStatus
if status == .unknown {
reach = false;
}
else if status == .notReachable {
reach = false;
}
else if status == .reachable(.ethernetOrWiFi) {
reach = true;
}
else if status == .reachable(.wwan) {
reach = true;
}
return reach;
}()
}
b. 二次封装Alamofire的GBNetwork文件
import UIKit
import Alamofire
import HandyJSON
class GBNetwork: NSObject {
struct responseData {
var request: URLRequest?
var response: HTTPURLResponse?
var json: AnyObject?
var error: NSError?
var data: Data?
}
class func requestWith(url: String, method:Alamofire.HTTPMethod, params: [String : Any]? ,result:@escaping(_ res: responseData? ,_ error: NSError?) -> ()) {
let reachAble = GBNetworkReachability.reachAbility.reachAble
if reachAble {
let headers : HTTPHeaders = [
"Content-type" : "application/json"
]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 15
manager.request(url, method: method, parameters: params, encoding: JSONEncoding.default, headers: headers).response { (response) in
let json:AnyObject! = try? JSONSerialization.jsonObject(with: response.data!, options: .allowFragments) as AnyObject
if json != nil {
let res = responseData(request: response.request, response: response.response, json: json, error: response.error as NSError? , data: response.data)
result(res,nil)
}
else {
let err = NSError(domain: "解析模型错误!", code: 120, userInfo: ["desc" : "解析模型错误!"])
result(nil,err)
}
}
}
else {
let err = NSError(domain: "当前网络异常", code: 110, userInfo: ["desc" : "当前网络异常!"])
result(nil,err)
}
}
}
c. 网络请求工具辅助解析成模型
import UIKit
import HandyJSON
class GBNetworkHelper: NSObject {
static let share = GBNetworkHelper();
struct result {
var code: Int?
var msg: String?
var data: [String: Any]?
}
func handleResponse(json: [String : Any]) -> result {
return result(code: json["code"] as? Int, msg: json["msg"] as? String, data: json)
}
// 登陆
func loadLogin(params:[String : Any], block:@escaping (_ item: BaseResponse<SampleData>) -> Void) {
let url = kBASE_URL + kLOGIN_URL
GBNetwork .requestWith(url: url, method: .post, params: params) { (response, error) in
if response != nil {
let dict = response?.json as! [String : Any]
if let obj = JSONDeserializer<BaseResponse<SampleData>>.deserializeFrom(dict: dict) {
block(obj)
}
} else {
}
}
}
// 获取用户信息
func loadUserInfo(params: [String : Any], block:@escaping(_ item: BaseResponse<GBUserInfoData>) -> Void) {
let url = kBASE_URL + kUSERINFO_URL
GBNetwork.requestWith(url: url, method: .post, params: params) { (response, error) in
if response != nil {
let dict = response?.json as! [String : Any]
if let obj = JSONDeserializer<BaseResponse<GBUserInfoData>>.deserializeFrom(dict: dict) {
block(obj)
}
} else {
}
}
}
// 机场列表
func loadAirportList(params: [String : Any] , block:@escaping(_ item : GBAirportListEntity) -> Void ) {
let url = kBASE_URL + kAIRPORTLIST_URL
GBNetwork.requestWith(url: url, method: .post, params: params) { (response, error) in
if response != nil {
let dict = response?.json as! [String : Any]
if let obj = JSONDeserializer<GBAirportListEntity>.deserializeFrom(dict: dict) {
block(obj)
}
} else {
}
}
}
}
二. model 文件
a. request模型
import UIKit
import HandyJSON
class BaseRequest<Params: HandyJSON, Protocol: HandyJSON>: HandyJSON {
var params: Params?
var `protocol` : Protocol?
required init() {}
}
struct BaseProtocol : HandyJSON {
var appkey: String?
var channel: String?
var lat: String?
var lng: String?
var os : String?
var token: String?
var ver: String?
}
struct BaseParams : HandyJSON {
}
b. response 模型
import UIKit
import HandyJSON
class BaseResponse<T: HandyJSON>: HandyJSON {
var code: Int?
var msg: String?
var data: T?
required init() {}
}
struct SampleData : HandyJSON {
var token: String?
}
c.数组数据
import UIKit
import HandyJSON
class GBAirportListEntity: HandyJSON {
var code: Int?
var msg : String?
var data: [AirportDataEntity]? = []
required init() {}
}
struct AirportDataEntity : HandyJSON {
var id : Int?
var airportNo: Int?
var airportName: String?
var longitude: Int?
var latitude: Int?
var address: String?
var cityId: Int?
var available: Bool?
var description: String?
}