Swift-Alamofire+HandyJSON(网络请求及转模型)

func loadData(_ latval:Double, _ lonval:Double) {
        weak var weakSelf = self
        // 参数
        var params = [String : Any]()
        params["cid"] = cid
        HWRequestManage<你的模型>.request(url: 请求url, params: params, success: { (model) in
            model.data // 就是你的模型    
        }) { (error) in
            print("错误信息:\(error)") 
        }
    }
    说明:
    请求的是模型数组只要添加[你的模型]即可
        HWRequestManage<[你的模型]>.request(url: 请求url, params: params, success: { (model) in
            model.data // 就是你的模型    
        }) { (error) in
            print("错误信息:\(error)") 
        }

请求模型(这个需要根据公司需求进行更改)

import UIKit
import HandyJSON
open class HWDataModel : HandyJSON {

    var data : T? // 主要数据
    var desc : String? = "" // 请求描述
    var status : Bool? = false // 请求成功与否
    var flag: String! // 标记
 
    /// 自定义 请求url
    var requestUrl : String = ""
    /// 自定义 请求数据
    var dataString : String = ""
    required public init() {}
}

封装

import UIKit
import HandyJSON
import Alamofire

class HWRequestManage {
    typealias valueBlock = ((HWDataModel)->())?
    /// 请求头
    private static func setHttpHeader()->[String: String] {
//        let time = String(Int(NSDate().timeIntervalSince1970)*1000)
//        let md5 = "\(time)123123".getMd5()
//        let header = ["key":md5,
//                      "times":time,
//                      "language":"CN"]
        let header = [String:String]()
        return header
    }
    
    /// get请求
    static public func request(url:String,params:[String:Any]? = nil,success:valueBlock,failture:((String)->())?){
        var requestUrl = url
        if url.contains("http") == false {
            requestUrl = "\(AppURL)\(url)"
        }
        Alamofire.request(requestUrl, method : HTTPMethod.get, parameters : params, encoding : URLEncoding.default, headers : setHttpHeader()).hw_responseString { (model:DataResponse>) in
            if success != nil,model.value != nil{
                success!(model.value!)
            }
            if failture != nil,model.error != nil{
                let error: HWError = model.error as! HWError
                switch  error {
                case  .string(let string):
                    failture!(string)
                }
            }
        }
    }
     ///   url:请求url  images:图片数组  name:图片数组的参数名  params:请求参数  success:请求成功回调 failture:请求失败回调
    static public func upImage(url: String, images:[UIImage], name:String, params: [String: String]? = nil, success:valueBlock, failture:((String)->())?) {
        var requestUrl = url
        if url.contains("http") == false {
            requestUrl = "\(AppURL)\(url)"
        }
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                for image in images {
                    // 对图片进行压缩
                    let imageData = UIImageJPEGRepresentation(image, 0.5)
                    // 如果需要上传多个文件,就多添加几个
                    multipartFormData.append(imageData!, withName: name, fileName: "ios.png", mimeType: "image/png")
                }
                if params != nil {
                    for (key, value) in params! {
                        multipartFormData.append((value.data(using: String.Encoding.utf8)!), withName: key)
                    }
                }
        },
            to: requestUrl,
            headers: setHttpHeader(),
            encodingCompletion: { (encodingResult) in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.hw_responseString(completionHandler: { (model:DataResponse>) in
                        if success != nil,model.value != nil{
                            success!(model.value!)
                        }
                        if failture != nil,model.error != nil{
                            let error: HWError = model.error as! HWError
                            switch  error {
                            case  .string(let string):
                                failture!(string)
                            }
                        }
                    })
                    // 获取上传进度
                    upload.uploadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
                        print("图片上传进度: \(progress.fractionCompleted)")
                    }
                case .failure(let encodingError):
                    //打印连接失败原因
                    print(encodingError)
                    if failture == nil {return}
                    failture!("网络请求错误")
                }
        })
    }
}
/// 对Alamofire进行扩展
extension DataRequest{
    @discardableResult
    public func hw_responseString(
        completionHandler: @escaping (DataResponse>) -> ())
        -> Self {
            let serializer = DataResponseSerializer> { (request, response, data, error) -> Result> in
                let requestUrl : String = String(describing: request?.url?.absoluteString ?? "")
                guard error == nil else {
                    print("请求失败:\(requestUrl)")
                    return .failure(HWError.string(string: "网络请求异常"))
                }
                if let response = response, hw_emptyDataStatusCodes.contains(response.statusCode) { return .success(HWDataModel()) }
                guard let validData = data else {
                    print("请求失败:\(requestUrl)")
                    return .failure(HWError.string(string: "数据请求异常"))
                }
                do {
                    let json = try JSONSerialization.jsonObject(with: validData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
                    let model = HWDataModel.deserialize(from: json)
                    if model != nil {
                        if model?.status == true{
                            model?.dataString = String(data:validData, encoding: String.Encoding.utf8) ?? ""
                            model?.requestUrl = requestUrl
                            return .success(model!)
                        }else{
                            print("请求失败:\(requestUrl)")
                            return .failure(HWError.string(string: (model?.desc) ?? ""))
                        }
                        
                    }else{
                        print("请求失败:\(requestUrl)")
                        return .failure(HWError.string(string: "数据请求异常"))
                    }
                } catch {
                    print("请求失败:\(requestUrl)")
                    return .failure(HWError.string(string: "网络请求异常"))
                }
            }
            return response(
                queue: DispatchQueue.main,
                responseSerializer: serializer,
                completionHandler: completionHandler
            )
    }
}
/// 对错误信息进行扩展
enum HWError: Error {
    case string(string:String)
}
/// A set of HTTP response status code that do not contain response data.
private let hw_emptyDataStatusCodes: Set = [204, 205]

你可能感兴趣的:(Swift-Alamofire+HandyJSON(网络请求及转模型))