您的位置:首页 > 理论基础 > 计算机网络

iOS项目中网络层实现自动转为对象的网络请求工具封装

2016-02-25 11:04 771 查看
以下是我项目中对网络层的工具类封装可以实现以下等功能

1\ 发送网络请求和进行回调处理

2\自动解析JSON对象 为 对象或对象数组

3\控制台彩色打印输出

4\统计请求次数和请求时间

前提:需以下第三方的支持:

import Alamofire

import SwiftyJSON

import Loggerithm

Reflect (用于字典转对象的OC第三方,需要的可以在github上搜索)

import Alamofire
import SwiftyJSON
import Loggerithm

class HULog_Pro :NSObject{
var urled = DomainName
var bianhao = ""
var netMethod = NetMethod.GET
var parm = [String : AnyObject]()
let fasongTime = NSDate()

func basicRequstLog_Begin(netMethod:NetMethod?,url: URLStringConvertible,parm:[String : AnyObject]?)->HULog_Pro{
//1 生成标号 和 请求方法统计
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
if let netMethods = netMethod{
switch netMethods{
case .GET:
bianhao = "GET_\(NetMethod.count_all++)_\(NetMethod.count_get++)"
case .POST:
bianhao = "POST_\(NetMethod.count_all++)_\(NetMethod.count_post++)"
case .PUT:
bianhao = "PUT_\(NetMethod.count_all++)_\(NetMethod.count_put++)"
case .PATCH:
bianhao = "PATCH_\(NetMethod.count_all++)_\(NetMethod.count_patch++)"
case .DELETE:
bianhao = "DELETE_\(NetMethod.count_all++)_\(NetMethod.count_DELETE++)"
break
}

self.netMethod = netMethods
}
//2 url处理
urled = url.URLString.toJPURL()

if parm == nil{
}else{
self.parm = parm!
}
if GlobalGuiderModle.guider_id != 0 && GlobalGuiderModle.brand_id != 0 && netMethod != .DELETE && urled.contain(DomainName) && appDelegate.DidjumptoMainTabBar{
if !self.parm.keys.contains("guider_id") && !self.parm.keys.contains("brand_id"){
self.parm["guider_id"] = GlobalGuiderModle.guider_id
self.parm["brand_id"] = GlobalGuiderModle.brand_id
}

}

//3 打印
HULOG.info("===========================================================================")

HULOG.info("\t��编号 :��\(bianhao)��的请求\t\t\t\t\t\t\t\t\t\t\t��\t\(bianhao)\t\t\(url)")
HULOG.info("\t��URL :" + "\(urled)")
if let parm = parm{

if let netMethods = netMethod{
switch netMethods{
case .GET:
HULOG.info("\t��GET:" + "\(parm)\n")
break
case .POST:
HULOG.info("\t��POST:" + "\(parm)\n")
break
case .PUT:
HULOG.error("\t��PUT:" + "\(parm)\n")
break
case .PATCH:
HULOG.error("\t��PATCH:" + "\(parm)\n")
break
case .DELETE:
HULOG.error("\t��DELETE:" + "\(parm)\n")
break
}
}
}
HULOG.info("\t")

HULOG.info("===========================================================================\n")
//        TestLog("请求:\(urled)",color:UIColor.lightGrayColor())
return self

}
func basicRequstLog_End(code:Int)->HULog_Pro{

UIApplication.sharedApplication().networkActivityIndicatorVisible = false

let time = -fasongTime.timeIntervalSinceNow
//3 打印
HULOG.info("===========================================================================")

HULOG.info("\t⛳️编号 :⛳️\(bianhao)⛳️的请求\t\t\t\t\t\t\t\t\t\t\t⛳️\t\(bianhao)\t\t\(code)")
HULOG.info("\t⛳️URL :" + "\(urled)")
//        HULOG.info("\t⛳️PARM:" + "\(parm)\n")

switch self.netMethod{
case .GET:
HULOG.info("\t⛳️方法:" + "GET\n")
HULOG.info("\t⛳️PARM:" + "\(parm)\n")
break
case .POST:
HULOG.info("\t⛳️方法:" + "POST\n")
HULOG.info("\t⛳️PARM:" + "\(parm)\n")
break
case .PUT:
HULOG.info("\t⛳️方法:" + "PUT\n")
HULOG.error("\t⛳️PARM:" + "\(parm)\n")
break
case .PATCH:
HULOG.info("\t⛳️方法:" + "PATCH\n")
HULOG.error("\t⛳️PARM:" + "\(parm)\n")
break
case .DELETE:
HULOG.info("\t⛳️方法:" + "DELETE\n")
HULOG.error("\t⛳️PARM:" + "\(parm)\n")
break
}

HULOG.info("\t⛳️用时 :" + "\(time)秒")
HULOG.info("\t⛳️状态码 :\(code)")

HULOG.info("===========================================================================\n")

if code == 403{
NSNotificationCenter.defaultCenter().postNotificationName("dandianDengLu", object: nil)
}else if code == 200{
if time > 5 && !self.urled.contain(subStr: "files/upload"){
TestLog("请注意该接口用时有:\(time.toDecimalStylString())s  接口\(urled)",color:UIColor.redColor())
}
//            TestLog("成功:\(urled)",color:UIColor.darkGrayColor())
}else{
TestLog("!!!\(code)!!!\(urled)",color:UIColor.redColor())
}
return self

}
}

class HU :NSObject{

/**
PATCH 简单请求

- parameter url:     地址
- parameter parm:    参数
- parameter succese: POST成功
- parameter failure: POST失败
*/
class func PATCH_Simple(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, succese: () -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.PATCH, url: url, parm: parm)
let method = Method.PATCH
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
succese()
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
POST 简单请求 返回String

- parameter url:     地址
- parameter parm:    参数
- parameter succese: POST成功
- parameter failure: POST失败
*/
class func POST_Simple_str(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, succese: () -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.POST, url: url, parm: parm)
let method = Method.POST
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseString(completionHandler: { (response) -> Void in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
succese()
default:
if let json = response.result.value {

failure(error: (statusCode: code, reason: json))

}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
})

}

/**
POST 简单请求

- parameter url:     地址
- parameter parm:    参数
- parameter succese: POST成功
- parameter failure: POST失败
*/
class func POST_Simple(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, succese: () -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.POST, url: url, parm: parm)
let method = Method.POST
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
succese()
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
POST 简单请求

- parameter url:     地址
- parameter parm:    参数
- parameter succese: POST成功
- parameter failure: POST失败
*/
class func POST_Simple_Dic(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, succese: (dic:JSON) -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.POST, url: url, parm: parm)
let method = Method.POST
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
if let json = response.result.value {
if IS_Not_Official_Domain_Name{
print(json)
}
succese(dic:JSON(json))
}else{
succese(dic:JSON.null)
}
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
简单PUT请求

- parameter url:     地址
- parameter parm:    参数
- parameter succese: 成功
- parameter failure: 失败
*/
class func DELETE_Simple(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, succese: () -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.DELETE, url: url, parm: parm)
let method = Method.DELETE
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
succese()
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
简单PUT请求

- parameter url:     地址
- parameter parm:    参数
- parameter succese: 成功
- parameter failure: 失败
*/
class func PUT_Simple(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, succese: () -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.PUT, url: url, parm: parm)
let method = Method.PUT
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
succese()
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
简单GET请求 _json

- parameter url:     地址
- parameter parm:    参数
- parameter succese: 成功
- parameter failure: 失败
*/
class func GET_Simple_Json(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, succese: (json:AnyObject) -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.GET, url: url, parm: parm)
let method = Method.GET
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200...204:
if let json = response.result.value {
if IS_Not_Official_Domain_Name{
print("编号:" + logInfo.bianhao + " 获得的数据:\n")
print(json)
}
succese(json:json)
}else{
failure(error: (statusCode: code, reason: "无数据"))
}

default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
简单GET请求 _JSONdic

- parameter url:     地址
- parameter parm:    参数
- parameter succese: 成功
- parameter failure: 失败
*/
class func GET_Simple_JSON(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, parmNil:Bool = false, succese: (JSON:JSON) -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.GET, url: url, parm: parm)
let method = Method.GET
if  parmNil { print("\(logInfo.bianhao) parm 置为nil ")}
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: parmNil ? nil : logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200...204:
if let json = response.result.value {
if IS_Not_Official_Domain_Name{
print(json)
}
succese(JSON:JSON(json))
}else{
succese(JSON:JSON.null)
}
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}
/**
简单GET请求

- parameter url:     地址
- parameter parm:    参数
- parameter succese: 成功
- parameter failure: 失败
*/
class func GET_Simple(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, succese: () -> () ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.GET, url: url, parm: parm)
let method = Method.GET
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
succese()
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
GET请求字典 转模型

- parameter netMethod:         Get方法请求模型
- parameter url:               路由地址
- parameter parm:              参数
- parameter completionHandler: 请求完成
*/
class func GET_Dic<T : Reflect>(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, completionHandler: (T) -> Void ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.GET, url: url, parm: parm)
let method = Method.GET
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
if let json = response.result.value {
if IS_Not_Official_Domain_Name{
print(json)
}
if let jsondic = json as? NSDictionary{
let modles = T.parse(dict: jsondic)
completionHandler(modles)
}else{
failure(error: (statusCode: code, reason: "\(json)"))
}

}
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
GET请求数组 转模型数组

- parameter netMethod:         Get方法请求模型数组
- parameter url:               路由地址
- parameter parm:              参数
- parameter completionHandler: 请求完成
*/
class func GET_Array<T : Reflect>(url: URLStringConvertible,parm:[String : AnyObject]?,showHud:Bool = false, completionHandler: ([T]) -> Void ,failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(.GET, url: url, parm: parm)
let method = Method.GET
if showHud{HUHud.wait()}
Alamofire.request(method, logInfo.urled, parameters: logInfo.parm, encoding:(method == Method.GET ? ParameterEncoding.URL : ParameterEncoding.JSON)).responseJSON { response in
if showHud{HUHud.clear()}
if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
if let json = response.result.value {
if IS_Not_Official_Domain_Name{
print(json)
}
let modles = T.parses(arr: json as! NSArray)
completionHandler(modles as! [T])
}
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")
failure(error: (statusCode: 999, reason: "响应异常 请求:\(logInfo.urled) 参数:\(parm)"))
}
}
}

/**
上传单个图片
- parameter zipTpey:   压缩类型  暂时没区分
- parameter imagedate: 需要上传的图片
- parameter success:   成功回调
- parameter falue:     失败回调
*/
class func postUpLoadImages(zipTpey:postUpLoadImagesZipTpey,imagedate:UIImage,success:((imageurl
:String)->()),failure:(error:(statusCode:Int,reason:String?))->()) -> (){

let logInfo = HULog_Pro().basicRequstLog_Begin(nil, url: "\(DomainName)/files/upload/images?zip=small", parm: nil)

let credential = NSURLCredential(user: GlobalGuiderModle.phoneNumber, password:GlobalGuiderModle.passWord, persistence: .ForSession)

self.UploadImageFileToServer("\(DomainName)/files/upload/images?zip=small", uploadImage: imagedate, imageType: ImageType.Png)
.authenticate(usingCredential: credential).responseJSON { response in

if let code = response.response?.statusCode{
logInfo.basicRequstLog_End(code)
switch code{
case 200:
if let json = response.result.value {
if let srt = JSON(json)["urls"][0].string{

success(imageurl:srt)
}else{
failure(error: (statusCode: code, reason: "url解析错误"))
}

}
default:
if let json = response.result.value {
if let error_description = JSON(json)["error_description"].string{
HULOG.error("\(code)" + "\(error_description)")
failure(error: (statusCode: code, reason: error_description))
}else{
HULOG.error("\(code)" + "无错误描述")
failure(error: (statusCode: code, reason: "无错误描述"))
}
}else{
HULOG.error("\(code)" + "返回数据为空")
failure(error: (statusCode: code, reason: "返回数据为空"))
}
}
}else{
HULOG.error("json为空")

}
}

}
}

enum NetMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"

case DELETE = "DELETE"

static var count_get = 0
static var count_post = 0
static var count_put = 0
static var count_patch = 0
static var count_DELETE = 0
static var count_all = 0
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 网络 控制台