我已经使用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)
}
}
在上面的课程中,我只提到了两个变量,即位置和地址,因为我只想在表视图中显示这两个值。
但是在获取结果之后,在下面的这一部分中,我无法进入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响应中,我想获取与名称和附近地区相关的数据。
答案 0 :(得分:1)
请在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)"
}
}