通常网络请求返回的是JSON数据,使用ObjectMapper可以让JSON数据直接转化为对象,而使用Alamofire进行网络请求时,使用AlamofireObjectMapper可以直接返回对象,更加简洁。
###CocoaPods 导入AlamofireObjectMapper
'AlamofireObjectMapper', '~> 3.0'```这里采用的Alamofire的测试接口 https://httpbin.org/get 在浏览器中打开可以看到JSON格式的数据: ```JSON { "args": {}, "headers": { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Cache-Control": "max-age=0", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0" }, "origin": "202.115.52.218", "url": "https://httpbin.org/get" }
|
根据该JSON的数据格式创建以下两个Mapper类分别对应整个字典和key值为“header”的字典。将JSON中的数据与对象中的数据一一建立转化关系。
import Foundation import ObjectMapper class ResponseHeader: Mappable { var accept : String? var acceptEncoding : String? var acceptLanguage : String? var cacheControl : String? var host : String? var userAgent : String? required init?(_ map: Map) { } func mapping(map: Map) { accept <- map["Accept"] acceptEncoding <- map["Accept-Encoding"] acceptLanguage <- map["Accept-Language"] cacheControl <- map["Cache-Control"] host <- map["Host"] userAgent <- map["User-Agent"] } }
|
import Foundation import ObjectMapper class MyResponse: Mappable { var args : NSDictionary? var headers : ResponseHeader? var origin : String? var url : String? required init?(_ map: Map) { } func mapping(map: Map) { args <- map["args"] headers <- map["headers"] origin <- map["origin"] url <- map["url"] } }
|
用Alamofire获取对象
func webRequst() { let url = "https://httpbin.org/get" Alamofire.request(.GET, url).responseObject { (response: Response<MyResponse, NSError>) in let myResponse = response.result.value print(myResponse?.url) if let header = myResponse?.headers{ print(header.userAgent) } } }
|