前言:
pod 'Alamofire', '5.4.4'
pod 'HandyJSON', '5.0.3-beta'
Xcode 13.2
headers 里面内容可看我前面的文章 获取设备信息
import HandyJSON
import Alamofire
import CocoaLumberjack
// MARK: 5.getter
private static let msgNetError = "网络错误,请联网后点击重试"
private static let msgDataError = "获取网络数据失败"
private static let manager = NetworkReachabilityManager()
private class var headers: HTTPHeaders {
get {
let head: HTTPHeaders = [
"iphone_name": iphone_name,
"device_name": device_name,
"device_model": device_model,
"device_IDFA": device_idfa,
"system_name": system_name,
"system_version": system_version,
"app_version": app_version,
]
return head
}
}
///返回数据类型
enum HTTPDataType: Int {
case one //单个 model
case more //数组 model
case text //字符串
}
///后台返回数据类型
struct netResponseData: HandyJSON {
var code: Int = 0
var msg: String?
var data: Any?
}
///返回数据类型
enum HTTPDataType: Int {
case one //单个 model
case more //数组 model
case text //字符串
}
///后台返回数据类型
struct netResponseData: HandyJSON {
var code: Int = 0
var msg: String?
var data: Any?
}
下面就是网络请求了,总体都放在
public class Networking {
}
返回单 model 网络请求
public class func request<T:HandyJSON>(url:String,
modelType: T.Type,
method: HTTPMethod = .post,
parameters: [String: String] = [:],
successBlock: @escaping (_ type: HTTPResultType, _ model: T?, _ msg:String) -> Void){
var encoding:ParameterEncoding = URLEncoding.default
if method == .post {
encoding = JSONEncoding.default
}
var dict = parameters
if token.isEmpty == false {
dict["token"] = token
}
AF.request(url, method: method, parameters: dict, encoding: encoding, headers: headers).responseJSON { (data) in
DDLogInfo("\n<请求url>:\n\(url) \n<请求参数>:\n\(String(describing: dict)) \n<请求头>:\n\(headers) \n<返回结果>:\n\(data) ")
responseData(.one, data, modelType) { (type, model, _, _, msg) in
successBlock(type, model, msg)
}
}
}
返回数组 model 网络请求
public class func request<T:HandyJSON>(url:String,
modelType: [T].Type,
method: HTTPMethod = .post,
parameters: [String: String] = [:],
successBlock: @escaping (_ type: HTTPResultType, _ models: [T?], _ msg:String) -> Void){
var encoding:ParameterEncoding = URLEncoding.default
if method == .post {
encoding = JSONEncoding.default
}
var dict = parameters
if token.isEmpty == false {
dict["token"] = token
}
AF.request(url, method: method, parameters: dict, encoding: encoding, headers: headers).responseJSON { (data) in
DDLogInfo("\n<请求url>:\n\(url) \n<请求参数>:\n\(String(describing: dict)) \n<请求头>:\n\(headers) \n<返回结果>:\n\(data) ")
responseData(.more, data) { (type, _, models, _, msg) in
successBlock(type, models, msg)
}
}
}
返回 string 类型网络请求
public class func request(url:String,
method: HTTPMethod = .post,
parameters: [String: String] = [:],
successBlock: @escaping (_ type: HTTPResultType, _ result: String, _ msg: String) -> Void){
var encoding:ParameterEncoding = URLEncoding.default
if method == .post {
encoding = JSONEncoding.default
}
var dict = parameters
if token.isEmpty == false {
dict["token"] = token
}
AF.request(url, method: method, parameters: dict, encoding: encoding, headers: headers).responseJSON { (data) in
DDLogInfo("\n<请求url>:\n\(url) \n<请求参数>:\n\(String(describing: dict)) \n<请求头>:\n\(headers) \n<返回结果>:\n\(data) ")
responseData(.text, data, netResponseData.self) { (type, _, _, result, msg) in
successBlock(type, result, msg)
}
}
}
上传图片网络请求
(备注:此处只是做单个 model 返回样式处理,当然你也可以调整)
public class func request<T:HandyJSON>(url:String,
modelType: T.Type,
imageData: (Data, String),
successBlock: @escaping (_ type: HTTPResultType, _ model: T?, _ msg:String) -> Void) {
AF.upload(multipartFormData: { (fromData) in
if imageData.1 == "GIF" {
fromData.append(imageData.0, withName: "file", fileName: "file.gif", mimeType: "image/gif")
} else {
fromData.append(imageData.0, withName: "file", fileName: "file.jpg", mimeType: "image/png,image/jpeg,image/jpg")
}
}, to: url, headers: headers).responseJSON { (data) in
DDLogInfo("\n<请求url>:\n\(url) \n<请求参数>:\n nil \n<请求头>:\n\(headers) \n<返回结果>:\n\(data) ")
responseData(.one, data, modelType) { (type, model, _, _, msg) in
successBlock(type, model, msg)
}
}
}
下面就是整体的数据请求处理了
class func responseData<T:HandyJSON>(
_ type: HTTPDataType,
_ response: AFDataResponse<Any>,
_ modelType: T.Type? = nil,
_ modelTypes: [T].Type? = nil,
_ finished: @escaping (_ type:HTTPResultType, _ model: T?, _ models: [T?], _ result: String, _ msg: String) -> Void) {
if let obj = JSONDeserializer<netResponseData>.deserializeFrom(dict: response.value as? [String:Any]) {
let message = obj.msg ?? msgNetError
if obj.code == -1 {
NotificationCenter.default.post(name: .net_login_reset, object: ["message":message])
return finished(.failure, nil, [], "", message)
}
if obj.code == 1 {
switch type {
case .one:
let model = T.deserialize(from: obj.data as? [String: Any])
return finished(.success, model, [], "", message)
case .more:
let models = [T].deserialize(from: obj.data as? [Any]) ?? []
return finished(.success, nil, models, "", message)
default:
let result = (obj.data as? String) ?? ""
return finished(.success, nil, [], result, message)
}
} else {
return finished(.failure, nil, [], "", message)
}
} else {
return finished(.failure, nil, [], "", msgNetError)
}
}
举个栗子🌰
Networking.request(url: url,
modelType: LoginModel.self,
parameters: dict) { (httpType, model, msg) in
if httpType == .success {
finishBack(true, msg)
} else {
finishBack(false, msg)
}
}
此处仅做笔记,如有不足,请各位大神指出