Alamofire responseArray keyPath 的字符串数组
Alamofire responseArray String array for keyPath
我有一个休息电话,其中 returns 字符串数组 [String] for keyPath "data",例如...
{
"data": [
"1",
"3",
"5",
"2",
"4",
"9"
]
}
我正在尝试通过 responseArray(keyPath: "data")
获取它,但在第 *.responseArray(keyPath: "data") {(response: DataResponse<[String]>) in*
行出现编译错误
Cannot convert value of type '(DataResponse<[String]>) -> ()' to expected argument type '(DataResponse<[_]>) -> Void'
部分请求示例
alamofireManager.request(url)
.responseArray(keyPath: "data") {(response: DataResponse<[String]>) in
if response.result.isSuccess {
if let data = response.result.value {
//process success
} else {
// handle error
}
}
...
你们有人知道怎么做吗?
问题是字符串不可映射。根据 https://github.com/Hearst-DD/ObjectMapper/issues/487,这些是建议的解决方案:
In this situation I would recommend accessing the data directly from the Alamofire response. You should be able to simply cast it to [String].
Alternatively, you may be able to subclass String and make the subclass Mappable, however I think that is more work than necessary for the your situation
使用Swift的4 Codable(无外部依赖):
struct APIResponse: Decodable {
let data: [String]
}
let url = "https://api.myjson.com/bins/1cm14l"
Alamofire.request(url).responseData { (response) in
if response.result.isSuccess {
if let jsonData = response.result.value,
let values = try? JSONDecoder().decode(APIResponse.self, from: jsonData).data {
//process success
print(values)
} else {
// handle error
}
}
}
我有一个休息电话,其中 returns 字符串数组 [String] for keyPath "data",例如...
{
"data": [
"1",
"3",
"5",
"2",
"4",
"9"
]
}
我正在尝试通过 responseArray(keyPath: "data")
获取它,但在第 *.responseArray(keyPath: "data") {(response: DataResponse<[String]>) in*
Cannot convert value of type '(DataResponse<[String]>) -> ()' to expected argument type '(DataResponse<[_]>) -> Void'
部分请求示例
alamofireManager.request(url)
.responseArray(keyPath: "data") {(response: DataResponse<[String]>) in
if response.result.isSuccess {
if let data = response.result.value {
//process success
} else {
// handle error
}
}
...
你们有人知道怎么做吗?
问题是字符串不可映射。根据 https://github.com/Hearst-DD/ObjectMapper/issues/487,这些是建议的解决方案:
In this situation I would recommend accessing the data directly from the Alamofire response. You should be able to simply cast it to [String].
Alternatively, you may be able to subclass String and make the subclass Mappable, however I think that is more work than necessary for the your situation
使用Swift的4 Codable(无外部依赖):
struct APIResponse: Decodable {
let data: [String]
}
let url = "https://api.myjson.com/bins/1cm14l"
Alamofire.request(url).responseData { (response) in
if response.result.isSuccess {
if let jsonData = response.result.value,
let values = try? JSONDecoder().decode(APIResponse.self, from: jsonData).data {
//process success
print(values)
} else {
// handle error
}
}
}