首页 > 解决方案 > 无法获取 google map api 响应来解析

问题描述

我已经使用 google api 来获取附近的位置。我已经进行了 api 调用并且也得到了正确的结果(json 响应)。

这是我为解析 json 响应而制作的模型类

class Locations: Codable {

  var locationName: String?
  var locationAddress: String?

  enum CodingKeys: String, CodingKey {
    case locationName = "name"
    case locationAddress = "vicinity"

  }

  required init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    locationName = try? values.decode(String.self, forKey: .locationName)
    locationAddress = try? values.decode(String.self, forKey: .locationAddress)

  }

  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(locationName, forKey: .locationName)
    try container.encode(locationAddress, forKey: .locationAddress)

  }
}

在上面的课程中,我只提到了两个变量,即位置和地址,因为我只想在我的 tableview 上显示这两个值。

但是在获取结果之后,在下面的这一部分中,我无法进入 if let 条件

WebServiceClient.shared.getNearbyLocationsList(withParameters: parameters, lattitude: lattitude, longitude: longitude) { [weak self] (isSuccess, result) in
      guard let `self` = self else { return }
      if isSuccess, result != nil {
        print("Successfully fetched nearby locations!")

//I have data in the result but it is not going into the if-let condition.
        if let productService = result?["results"] as? [[String: Any]] ,
          let jsonData = try? JSONSerialization.data(withJSONObject: productService as Any, options: []),
          let locationsList = try? JSONDecoder().decode([Locations].self, from: jsonData) {
          self.locationsList = locationsList          

        }

这是 api 响应的一小部分...

{
   "html_attributions" : [],
   "next_page_token" : "CsQEQAIAAG….”,
   "results" : [
      {
         "geometry" : {
            "location" : {
               "lat" : 19.07456,
               "lng" : 74.86545
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 19.2456,
                  "lng" : 74.98456
               },
               "southwest" : {
                  "lat" : 18.8564,
                  "lng" : 76.7745645
               }
            }
         },
         "icon" : “sdf.png",
         "id" : "2e66c82c2e8d7149bd7e026089ff5dedb8346bd5",
         "name" : "Mumbai",
         "photos" : [
            {
               "height" : 2304,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/111225135501811810933/photos\"\u003eRamkrishna Pudasaini\u003c/a\u003e"
               ],
               "photo_reference" : "CmRZAAAA4WHsIxpFh…”,
               "width" : 3456
            }
         ],
         "place_id" : "Chbdfbdfb_tpF0",
         "reference" : "ChIJbnfgh54_tpF0",
         "scope" : "GOOGLE",
         "types" : [ "locality", "political" ],
         "vicinity" : "Mumbai"
      }
],
“status” : “OK”
}

从这个 api 响应中,我想获取与名称和附近相关的数据。

标签: iosswiftapi

解决方案


请在 do-catch 语句中移动 JSONDecoder 部分,它将起作用。

if let productService = result?["results"] as? [[String: Any]] ,
          let jsonData = try? JSONSerialization.data(withJSONObject: productService as Any, options: []) {

     do {

         let locationsList = try JSONDecoder().decode([LocationInfo].self, from: jsonData)
         self.locationsList = locationsList          

      } catch {

         print("error \(error)"

      }

 }

推荐阅读