Swift学习笔记(三)Alamofire二次封装

Alamofire如何集成可以查看这里

创建一个BaseHttpClient类,在Alamofire基础之上二次封装

func requestURL(url:String, params:Dictionary, method:HTTPMethod, success:((_ responseObj:Dictionary?) -> Void)?, failure:((_ e:Error) -> Void)?) -> Void {
    request(url, method: method, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
        if(response.error == nil){
            success!(response.result.value as? Dictionary)
        }else{
            failure!(response.error!)
        }
    }
}

创建一个BaseHttpClient的子类,命名为HttpClient,主要用于业务接口的URL、入参、回参做第一层处理

例如业务接口返回格式如下图所示:Controller和View层需要使用的是data键对应的内容

Swift学习笔记(三)Alamofire二次封装_第1张图片
image.png

使用二次封装的requestURL方法,处理回参数据,只有当status=200时才去解析data键值,其他情况均failure Block一个HttpExceptiont对象,用于提示用户错误信息

func requestPath(Url:String, Params:Dictionary, Method:HTTPMethod, success :((_ responseObj:Dictionary?) -> Void)?, failure:((_ e:HttpException) -> Void)?) -> Void {

    self.requestURL(url: Url, params: Params, method: Method, success: { (responseObj) in

        //处理业务接口
        let status = responseObj!["status"] as! Int//获取status

        if status == 200{//取data对应的键值,Block success

            success?(responseObj!["data"] as? Dictionary)
        }else{//初始化HttpException对象,Block failure

            let e = HttpException.init(code: status, msg: responseObj!["message"] as! String)
            failure!(e)
        }
    }) { (e) in

        //初始化HttpException对象,Block failure
        let error = e as NSError
        let e = HttpException.init(code: error.code, msg: error.description)
        failure!(e)
    }
}

另外我们可以在HttpClient类中添加URL拼接、修改header、入参数据加密等

还可以将请求封装成类方法:

//GET
class func GET(url:String, params:Dictionary, success:((_ responseObj:Dictionary?) -> Void)?, failure:((_ e:HttpException) -> Void)?) -> Void {
    HttpClient().requestPath(Url: url, Params: params, Method: .get, success: { (responseObj) in
        success!(responseObj)
    }) { (e) in
        failure!(e)
    }
}

在其他文件中可以这样调用GET请求:

HttpClient.GET(url: requestURL, params: param, success: { (responseObj) in

}) { (e) in

}

你可能感兴趣的:(Swift学习笔记(三)Alamofire二次封装)