AlamofireObjectMapper框架的基本使用以及二次封装
2016-10-10 23:38
741 查看
AlamofireObjectMapper框架的基本使用以及二次封装
AlamofireObjectMapper框架是基于Alamofire和ObjectMapper框架上使用的,它是对Alamofire框架中的Request进行的扩展。AlamofireObjectMapper能够实现获取服务器数据并转化成自己定义的模型一步到位,省略了大量的操作。
使用AlamofireObjectMapper框架需要在CocoaPods导入(需要使用Swift3.0或者Swift2.0+版本的可自己选择,我这里是Swift2.3语法版本的)
在这个框架当中我最常用的方法就是这个
1、服务器返回的数据
在一个项目中很多的类都会使用网络请求,如果每次都使用上述方法来我们的项目就中了“AlamofireObjectMapper”的毒了,下面是个人对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!上面是我个人对它的封装,如果哪个同学有更好的做法,请记得分享给我
。
相关文章推荐
- 对AlamofireObjectMapper进行二次封装
- IOS网络操作-使用Alamofire和ObjectMapper处理JSON转对象
- OkHttp的基本使用以及二次封装
- 技术共享之数据库框架GreenDao的使用以及二次封装
- android的技术分解以及Retrofit源码分析以及MVP框架封装使用
- sqlite3 的基本使用 以及封装使用
- react native 使用fetch进行网络请求(https),解决SSLHandshake问题,以及怎样进行二次封装
- [快速学会Swift第三方库]AlamofireObjectMapper
- Alamofire +ObjectMapper模型: 上传音频。
- OkHttp框架从入门到放弃,解析图片使用Picasso裁剪,二次封装OkHttpUtils,Post提交表单数据
- Swift学习记录 - Alamofire 4.0.1网络库基本使用(持续更新...)
- Jackson框架提供的JsonGenerator ObjectMapper以及JSONObject 、JSONArray学习
- Jackson框架提供的JsonGenerator ObjectMapper以及JSONObject 、JSONArray学习
- 使用express.js框架一步步实现基本应用以及构建可扩展的web应用
- J2EE项目系列(四)--SSM框架构建积分系统和基本商品检索系统(Spring+SpringMVC+MyBatis)(3)Ajax使用详解(级联列表)以及企业级报表Excel导入导出实现
- 微信小程序基本的开发框架抽取,包括网络请求的二次封装,页面状态管理,常见页面模板封装
- 关于xutils3.0框架的封装以及抽取,方便使用
- 微信开发准备(三)——框架以及工具的基本使用
- OkHttp框架从入门到放弃,解析图片使用Picasso裁剪,二次封装OkHttpUtils,Post提交表单数据
- swift Alamofire+ObjectMapper——swift(学习九)