gpt4 book ai didi

swift - 从 AF responseJSON 获取数据

转载 作者:行者123 更新时间:2023-11-28 11:34:41 25 4
gpt4 key购买 nike

我有处理位置数据的代码,因此我可以提取可以匿名化数据的详细信息——例如,如果我的地点 API 说它是 _type:“Building”和 building:“Safeway”——我可以保存数据作为纬度/经度的 md5:“safeway”,并且在检查我的位置数据时所有 safeways 看起来都一样。这也是我想要的。

static func getLocationData(location: CLLocation, _ callback: @escaping (CLLocation?) -> Void) {
let parameters = [
"q": location.coordinate.latitude.description + "," + location.coordinate.longitude.description,
"key": Places.OPENCAGEDATA_API_KEY
]

AF.request(Places.uri, method: .get, parameters: parameters, encoding: URLEncoding(destination: .queryString)).responseJSON { response in
switch response.result {

case .success(let json):
print(json)
DispatchQueue.main.async {

callback(location)

}
case .failure(let error):
print(error)

callback(nil)
}
}
}

如我所见,此交易有效:

{
documentation = "https://opencagedata.com/api";
licenses = (
{
name = "CC-BY-SA";
url = "https://creativecommons.org/licenses/by-sa/3.0/";
},
{
name = ODbL;
url = "https://opendatacommons.org/licenses/odbl/summary/";
}
);
rate = {
limit = 2500;
remaining = 2496;
reset = 1556150400;
};
results = (
{
annotations = {
DMS = {
lat = "MYLAT N";
lng = "MYLONG W";
};
FIPS = ...

但现在 json 只是一种恰好打印得很好的 Any 类型。例如,我如何获得 json.results.annotations.DMS.lat

最佳答案

你可以试试

 if let res = json as? [String: Any]{
if let inner = res["results"] as? [[String: Any]] {
for item in inner {
if let ert = item["annotations"] as? [[String: Any]] {
for ann in ert {
print(ann["lat"])
}
}
}
}
}

你也可以做

struct Root: Codable {
let results: [DataClass]
}

struct DataClass: Codable {
let annotations: [Anno]
}

struct Anno: Codable {
let lat:Double // or String as in your question it's a String IDN if this is a description
}

do {
guard let data = try JSONSerialization.data(withJSONObject: json, options: []) else { return }
let locationObject = try JSONDecoder().decode(Root.self, from:data)
} catch {
print(error)
}

关于swift - 从 AF responseJSON 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55831439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com