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
原创粉丝点击