通常网络请求返回的是JSON数据,使用ObjectMapper可以让JSON数据直接转化为对象,而使用Alamofire进行网络请求时,使用AlamofireObjectMapper可以直接返回对象,更加简洁。
Podfile文件内容为如下:
source'https://github.com/CocoaPods/Specs.git'
platform:ios,'9.0'
use_frameworks!
target'Web'do
pod'AlamofireObjectMapper','~> 3.0'
end
xcodeproj'Desktop/Web/Web.xcodeproj'
target后面为工程名,最后一行为工程路径(这里的Web是我的工程名)
额外操作:
Target->工程名->Build Settings->Search Paths->User Header Search Paths处添加AlamofireObjectMapper所在的目录:
最后在你需要用到AlamofireObjectMapper的类中加上:
importAlamofireObjectMapper
创建 Mappable 对象
{
"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 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) {
}
//映射heades字典中的所有键值
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获取对象
webRequst() { let url = "https://httpbin.org/get" //注意返回的类型为Alamofire.request(.GET, url).responseObject { (response: Response) in
let myResponse = response.result.value
print(myResponse?.url)
if let header = myResponse?.headers{
print(header.userAgent)
}
}
}
打印内容:
Optional("https://httpbin.org/get")
Optional("Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))")
Alamofire的使用:[快速学会Swift第三方库] Alamofire篇
ObjectMapper在非Alamofire请求下的使用:GitHub-ObjectMapper主页