【发布时间】:2021-04-13 05:22:36
【问题描述】:
我有这个 JSON 响应 -
我已关注this blog 进行 api 调用并解码响应。他们的代码 sn-p -
func searchPlaces(query: String) {
let urlStr = "\(mapbox_api)\(query).json?access_token=\(mapbox_access_token)"
print(urlStr)
Alamofire.request(urlStr, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseSwiftyJSON { (dataResponse) in
if dataResponse.result.isSuccess {
let resJson = JSON(dataResponse.result.value!)
if let myjson = resJson["features"].array {
for itemobj in myjson ?? [] {
try? print(itemobj.rawData())
do {
let place = try self.decoder.decode(Feature.self, from: itemobj.rawData())
self.searchedPlaces.add(place)
self.tableView.reloadData()
} catch let error {
if let error = error as? DecodingError {
print(error.errorDescription)
}
}
}
}
}
if dataResponse.result.isFailure {
let error : Error = dataResponse.result.error!
}
}
}
在这里,他们通过 for 循环获取 每个功能项,然后对其进行解码并将其附加到数组中。 我想通过使用 URLSession转换这个。但是这部分他们使用了 dataResponse.result 这在 URLSession 中不可用 -
if dataResponse.result.isSuccess {
let resJson = JSON(dataResponse.result.value!)
if let myjson = resJson["features"].array {
for itemobj in myjson ?? [] {
try? print(itemobj.rawData())
do {
let place = try self.decoder.decode(Feature.self, from: itemobj.rawData())
self.searchedPlaces.add(place)
self.tableView.reloadData()
}
那么如何使用 URLSession 转换这个 dataResponse.result 部分?
可编码结构(这是用于 alamofire 请求的)-
struct Feature: Codable {
var id: String!
var type: String?
var matching_place_name: String?
var place_name: String?
var geometry: Geometry
var center: [Double]
var properties: Properties
}
struct Geometry: Codable {
var type: String?
var coordinates: [Double]
}
struct Properties: Codable {
var address: String?
}
【问题讨论】:
-
我不明白目标。 Alamofire 和 URLSession dataTask 都可以返回相同的数据,Alamofire 甚至反序列化为多种格式。
标签: ios swift alamofire codable urlsession