【问题标题】:Convert Alamofire Request to URLSession Request将 Alamofire 请求转换为 URLSession 请求
【发布时间】: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


【解决方案1】:

如果您想使用URLSession,这是一个可能的解决方案:

let session = URLSession.shared
let url = URL(string: "https://YOUR_URL")!
let task = session.dataTask(with: url, completionHandler: { data, response, error in

    // Check the response
    print(response)
            
   // Check if an error occured
   if error != nil {
      // HERE you can manage the error
      print(error)
      return
   }
            
   // Serialize the data into an object
   do {                
      let json = try JSONDecoder().decode(FullResponse.self, from: data!)

      //try JSONSerialization.jsonObject(with: data!, options: [])
      print(json)
      DispatchQueue.main.async {
         // pass data to main thread
      }

   } catch {
      print("Error during JSON serialization: \(error.localizedDescription)")
   }
})
task.resume()

您可能需要为 FullResponse 创建一个结构。

【讨论】:

  • 这不是我的问题。我的问题是如何获取 JSON 的一部分,然后使用它来使用可编码的代码
  • 完整回复:let json = try JSONSerialization.jsonObject(with: data!, options: []),你需要的部分就拿去吧。
  • if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) { let feature = jsonObject["features"] print(feature) } 得到 'Any' 类型的值没有下标' 错误
  • 检查/打印 jsonObject。
  • 我建议使用我的答案代码,但如果您更喜欢使用 JSONSerialization.jsonObject,您可能需要使用if let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] { let features = jsonObject["features"] print(feature) }
猜你喜欢
  • 2019-09-21
  • 1970-01-01
  • 2021-06-30
  • 2018-04-16
  • 1970-01-01
  • 2021-02-06
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多