AlamoFire + ObjectMapper,如何让函数获取 Mappable 类型的参数?
Posted
技术标签:
【中文标题】AlamoFire + ObjectMapper,如何让函数获取 Mappable 类型的参数?【英文标题】:AlamoFire + ObjectMapper, how to have a function take a parameter of something that is of type Mappable? 【发布时间】:2016-06-09 01:58:44 【问题描述】:我目前有一个函数:
func getJSONDataDictionary (accessToken: String, response: Mappable, url: String)
let headers = [
"Cache-Control": "no-cache",
"Authorization": "bearer \(accessToken)"
]
Alamofire.request(.GET, url, encoding: .JSON, headers: headers)
.responseObject (response: Response<response, NSError>) in
let JSONDict = response.result.value
我想为响应参数传入一个 Mappable 类型的类(用于识别类是否符合 ObjectMapper 协议的类)。使用现在的代码方式,我得到一个错误“响应不是类型”。我可以对这个函数做些什么,让它接受一个 Mappable 参数吗?
【问题讨论】:
【参考方案1】:错误消息指出您的参数 result 不是类型,但它不是。 可映射是一个协议。
我建议您将函数设为通用,如下所示:
func getJSONDataDictionary< T: Mappable>(accessToken: String, response: T, url: String)
let headers = [
"Cache-Control": "no-cache",
"Authorization": "bearer \(accessToken)"
]
Alamofire.request(.GET, url, encoding: .JSON, headers: headers)
.responseObject (response: Response<response, NSError>) in
let JSONDict = response.result.value
泛型类型 T 将受限于 Mappable 协议。
【讨论】:
【参考方案2】:你可以这样做:
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let pjson = attendences.toJSONString(prettyPrint: false)
let data = (pjson?.data(using: .utf8))! as Data
request.httpBody = data
Alamofire.request(request).responseJSON (response) in
print(response)
【讨论】:
【参考方案3】:let query_url = Constant.BASE_URL + Constant.ENDPOINT
var urlRequest = URLRequest(url: URL(string: query_url)!)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue("Cache-Control", forHTTPHeaderField: "no-cache"")
urlRequest.addValue("Authorization", forHTTPHeaderField:"bearer \(accessToken)")
let req = Alamofire.request(urlRequest)
req.responseObject (response: DataResponse<Model>) in
let value = response.result.value
print(value?.data?.count)
【讨论】:
以上是关于AlamoFire + ObjectMapper,如何让函数获取 Mappable 类型的参数?的主要内容,如果未能解决你的问题,请参考以下文章
Swift 3 的 ObjectMapper 和 Alamofire 问题 Alamofire 4 的 Alamofire 版本
Swift/Alamofire/ObjectMapper:忽略零值
AlamoFire + ObjectMapper,如何让函数获取 Mappable 类型的参数?
如何使用 AlamoFire/ObjectMapper 访问嵌入在 JSON 字典中的链接?