AlamofireObjectMapper框架的基本使用以及二次封装
来源:互联网 发布:淘宝商城靴子 编辑:程序博客网 时间:2024/05/17 23:49
AlamofireObjectMapper框架的基本使用以及二次封装
AlamofireObjectMapper框架是基于Alamofire和ObjectMapper框架上使用的,它是对Alamofire框架中的Request进行的扩展。AlamofireObjectMapper能够实现获取服务器数据并转化成自己定义的模型一步到位,省略了大量的操作。
使用AlamofireObjectMapper框架需要在CocoaPods导入(需要使用Swift3.0或者Swift2.0+版本的可自己选择,我这里是Swift2.3语法版本的)
pod 'Alamofire'pod 'ObjectMapper'pod 'AlamofireObjectMapper'
在这个框架当中我最常用的方法就是这个
public func responseObject<T: Mappable>(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, mapToObject object: T? = nil, context: MapContext? = nil, completionHandler: Response<T, NSError> -> Void) -> Self下面就通过具体的代码来讲解
1、服务器返回的数据
{ Data = { Content = Dsafdfsdfdsfdsfdfdf; DailyTime = "2016-07-13"; Files = ( { FileId = 665; FilePath = "/UploadFile/Img/DYQ/20160713/636040193973304167.png?width=68&height=68"; }, { FileId = 666; FilePath = "/UploadFile/Img/DYQ/20160713/636040193973404173.png?width=68&height=68"; }, { FileId = 667; FilePath = "/UploadFile/Img/DYQ/20160713/636040193973484177.png?width=68&height=68"; }, { FileId = 670; FilePath = "/UploadFile/Img/DYQ/20160713/636040194134223371.png?width=68&height=68"; } ); Id = 870; }; Id = 0; IsLeader = 0; IsLogin = 1; Message = "<null>"; NeedLoin = 1; Succeed = 1; list = { Content = Dsafdfsdfdsfdsfdfdf; DailyTime = "2016-07-13"; Files = ( { FileId = 665; FilePath = "/UploadFile/Img/DYQ/20160713/636040193973304167.png?width=68&height=68"; }, { FileId = 666; FilePath = "/UploadFile/Img/DYQ/20160713/636040193973404173.png?width=68&height=68"; }, { FileId = 667; FilePath = "/UploadFile/Img/DYQ/20160713/636040193973484177.png?width=68&height=68"; }, { FileId = 670; FilePath = "/UploadFile/Img/DYQ/20160713/636040194134223371.png?width=68&height=68"; } ); Id = 870; }; succeed = 1;})2、利用ObjectMapper框架设计模型如下:
struct ResultModel: Mappable { var data: DataModel? var id: Int = -1 var isLeader: Int = -1 var list: DataModel? init?(_ map: Map) {} mutating func mapping(map: Map) { data <- map["Data"] id <- map["Id"] isLeader <- map["IsLeader"] list <- map["list"] }}struct DataModel: Mappable { var content: String = "" var dailyTime: String = "" var files: [FilesModel]? init?(_ map: Map) {} mutating func mapping(map: Map) { content <- map["Content"] dailyTime <- map["DailyTime"] files <- map["Files"] }}struct FilesModel: Mappable { var fileId: Int = -1 var filePath: String = "" init?(_ map: Map) {} mutating func mapping(map: Map) { fileId <- map["FileId"] filePath <- (map["FilePath"], transfromOfCustomFunction()) } // 自己定义的某些操作的方法 func transfromOfCustomFunction() ->TransformOf<String , String>{ return TransformOf<String , String>.init(fromJSON: { (str) -> String? in return str! + "-Hello Word!" }, toJSON: { (str1) -> String? in return str1?.stringByReplacingOccurrencesOfString("-Hello Word!", withString: "") }) }}3、利用获取的数据并转换为Model
Alamofire.request(.POST, url, parameters: params).responseObject() { (response: Response<ResultModel, NSError>) in let resultModel = response.result.value! print("data = \(resultModel.data!), id = \(resultModel.id), isLeader = \(resultModel.isLeader)") print("-----------------------------") // 打印dataModel let dataModel = resultModel.data print("content = \(dataModel?.content), dailyTime = \(dataModel?.dailyTime)") print("-----------------------------") for filesModel in dataModel!.files! { print("fileId = \(filesModel.fileId), filePath = \(filesModel.filePath)") } }控制台打印如下:(成功转化)
data = DataModel(content: "Dsafdfsdfdsfdsfdfdf", dailyTime: "2016-07-13", files: Optional([NewStudy.FilesModel(fileId: 665, filePath: "/UploadFile/Img/DYQ/20160713/636040193973304167.png?width=68&height=68-Hello Word!"), NewStudy.FilesModel(fileId: 666, filePath: "/UploadFile/Img/DYQ/20160713/636040193973404173.png?width=68&height=68-Hello Word!"), NewStudy.FilesModel(fileId: 667, filePath: "/UploadFile/Img/DYQ/20160713/636040193973484177.png?width=68&height=68-Hello Word!"), NewStudy.FilesModel(fileId: 670, filePath: "/UploadFile/Img/DYQ/20160713/636040194134223371.png?width=68&height=68-Hello Word!")])), id = 0, isLeader = 0-----------------------------content = Optional("Dsafdfsdfdsfdsfdfdf"), dailyTime = Optional("2016-07-13")-----------------------------fileId = 665, filePath = /UploadFile/Img/DYQ/20160713/636040193973304167.png?width=68&height=68-Hello Word!fileId = 666, filePath = /UploadFile/Img/DYQ/20160713/636040193973404173.png?width=68&height=68-Hello Word!fileId = 667, filePath = /UploadFile/Img/DYQ/20160713/636040193973484177.png?width=68&height=68-Hello Word!fileId = 670, filePath = /UploadFile/Img/DYQ/20160713/636040194134223371.png?width=68&height=68-Hello Word!4、利用KeyPath转换指定字段为Model
Alamofire.request(.POST, url, parameters: params).responseObject(keyPath: "Data") { (response: Response<DataModel, NSError>) in // 打印dataModel let dataModel = response.result.value! print("content = \(dataModel.content), dailyTime = \(dataModel.dailyTime)") print("-----------------------------") for filesModel in dataModel.files! { print("fileId = \(filesModel.fileId), filePath = \(filesModel.filePath)") } }控制台打印如下:
content = Dsafdfsdfdsfdsfdfdf, dailyTime = 2016-07-13-----------------------------fileId = 665, filePath = /UploadFile/Img/DYQ/20160713/636040193973304167.png?width=68&height=68-Hello Word!fileId = 666, filePath = /UploadFile/Img/DYQ/20160713/636040193973404173.png?width=68&height=68-Hello Word!fileId = 667, filePath = /UploadFile/Img/DYQ/20160713/636040193973484177.png?width=68&height=68-Hello Word!fileId = 670, filePath = /UploadFile/Img/DYQ/20160713/636040194134223371.png?width=68&height=68-Hello Word!5、上面便是即是AlamofireObjectMapper的基本使用了,还有一个转化数组的方法,发夹可以参考这里查看详细的介绍。
在一个项目中很多的类都会使用网络请求,如果每次都使用上述方法来我们的项目就中了“AlamofireObjectMapper”的毒了,下面是个人对AlamofireObjectMapper框架的二次封装
protocol NetWorkingTool { }extension NetWorkingTool { /** 获取服务器数据,并转化为模型(对AlamofireObjectMapper进一步封装) - parameter url: url地址 - parameter params: 请求参数 - parameter keyPath: 需要转模型的数据字段 - parameter successBlock: 成功回调 - parameter errorBlock: 失败回调 */ func alRequestGetDataFormServers<T: Mappable>(url: String, params:[String: String]? = nil, keyPath: String? = nil, successBlock: (result: T) -> Void, errorBlock: (error: NSError) -> Void) { Alamofire.request(.POST, url, parameters: params).responseObject(keyPath: keyPath) { (response: Response<T, NSError>) in if let err = response.result.error { errorBlock(error:err) } else { successBlock(result: response.result.value!) } } } /** 获取服务器数据,并转化为模型,适用于一个字典数组(对AlamofireObjectMapper进一步封装) - parameter url: url地址 - parameter params: 请求参数 - parameter keyPath: 需要转模型的数据字段 - parameter successBlock: 成功回调 - parameter errorBlock: 失败回调 */ func alRequestGetDataFormServersCallbackArray<T: Mappable>(url: String, params:[String: String]? = nil, keyPath: String? = nil, successBlock: (result: [T]) -> Void, errorBlock: (error: NSError) -> Void) { Alamofire.request(.POST, url, parameters: params).responseArray(keyPath: keyPath) { (response:Response<[T], NSError>) in if let err = response.result.error { errorBlock(error:err) } else { successBlock(result: response.result.value!) } } }}应用例子:
requestGetDataFormServers(url, params: params, successBlock: { (result: ResultModel) in print("data = \(result.data!), id = \(result.id), isLeader = \(result.isLeader)") print("-----------------------------") // 打印dataModel let dataModel = result.data print("content = \(dataModel?.content), dailyTime = \(dataModel?.dailyTime)") print("-----------------------------") for filesModel in dataModel!.files! { print("fileId = \(filesModel.fileId), filePath = \(filesModel.filePath)") } }) { (error) in print("error = \(error)") }
控制台打印:
data = DataModel(content: "Dsafdfsdfdsfdsfdfdf", dailyTime: "2016-07-13", files: Optional([NewStudy.FilesModel(fileId: 665, filePath: "/UploadFile/Img/DYQ/20160713/636040193973304167.png?width=68&height=68-Hello Word!"), NewStudy.FilesModel(fileId: 666, filePath: "/UploadFile/Img/DYQ/20160713/636040193973404173.png?width=68&height=68-Hello Word!"), NewStudy.FilesModel(fileId: 667, filePath: "/UploadFile/Img/DYQ/20160713/636040193973484177.png?width=68&height=68-Hello Word!"), NewStudy.FilesModel(fileId: 670, filePath: "/UploadFile/Img/DYQ/20160713/636040194134223371.png?width=68&height=68-Hello Word!")])), id = 0, isLeader = 0-----------------------------content = Optional("Dsafdfsdfdsfdsfdfdf"), dailyTime = Optional("2016-07-13")-----------------------------fileId = 665, filePath = /UploadFile/Img/DYQ/20160713/636040193973304167.png?width=68&height=68-Hello Word!fileId = 666, filePath = /UploadFile/Img/DYQ/20160713/636040193973404173.png?width=68&height=68-Hello Word!fileId = 667, filePath = /UploadFile/Img/DYQ/20160713/636040193973484177.png?width=68&height=68-Hello Word!fileId = 670, filePath = /UploadFile/Img/DYQ/20160713/636040194134223371.png?width=68&height=68-Hello Word!根据KeyPath获取数据转换Model
requestGetDataFormServers(url, params: params, keyPath: "Data", successBlock: { (result: DataModel) in // 打印dataModel print("content = \(result.content), dailyTime = \(result.dailyTime)") print("-----------------------------") for filesModel in result.files! { print("fileId = \(filesModel.fileId), filePath = \(filesModel.filePath)") } }) { (error) in print("error = \(error)") }控制台打印:
content = Dsafdfsdfdsfdsfdfdf, dailyTime = 2016-07-13-----------------------------fileId = 665, filePath = /UploadFile/Img/DYQ/20160713/636040193973304167.png?width=68&height=68-Hello Word!fileId = 666, filePath = /UploadFile/Img/DYQ/20160713/636040193973404173.png?width=68&height=68-Hello Word!fileId = 667, filePath = /UploadFile/Img/DYQ/20160713/636040193973484177.png?width=68&height=68-Hello Word!fileId = 670, filePath = /UploadFile/Img/DYQ/20160713/636040194134223371.png?width=68&height=68-Hello Word!上面是我个人对它的封装,如果哪个同学有更好的做法,请记得分享给我。
0 0
- AlamofireObjectMapper框架的基本使用以及二次封装
- OkHttp的基本使用以及二次封装
- 对AlamofireObjectMapper进行二次封装
- okhttp的二次封装(基本使用)
- 技术共享之数据库框架GreenDao的使用以及二次封装
- Volley框架的二次封装
- Volley框架的二次封装
- 二次封装的GCD使用
- android UiAutomator基本api的二次封装
- Android二次封装的网络框架 AndNet
- Android网络框架AsyncHttpClient的二次封装
- android网络框架asyncHttpClient 的二次封装
- selenium二次封装的测试框架选择
- Xutils3网络框架的二次封装
- Volley框架二次封装
- 微信小程序基本的开发框架抽取,包括网络请求的二次封装,页面状态管理,常见页面模板封装
- Android——MVP架构OkHttp的二次封装以及RecyclerView的使用
- AFNetWorking使用及二次封装的好处
- 最全的Android源码目录结构详解
- SpringMVC——对Ajax的处理(包含 JSON 类型)
- camel笔记
- MACOS Sierra 10.12安全性与隐私没有任何来源选项
- Qt中嵌入OSG控件的方法
- AlamofireObjectMapper框架的基本使用以及二次封装
- Creating Great Teams: How Self-Selection Lets People Excel(读书笔记)
- 生产者消费者问题(C实现)
- linux partation
- Jackson属性和方法注解规避
- vs2015关于“当前不会命中断点 还没有为该文档加载任何符号”的解决方法
- 神曲当道,洗脑不断
- Struts2与ajax结合的缺点
- Android中的网络传输基本知识点