gpt4 book ai didi

ios - 将 Alamofire 结果保存为变量?

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

我一直在尝试找出如何将来自 Alamofire 的 JSON 响应的一部分保存为变量以生成 if 语句,但似乎找不到如何去做。

我编写了一段代码作为问题的示例,其中包含以下内容:

import UIKit
import Alamofire

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()


Alamofire.request("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44143256ee15e9c3f521ca062463dd8d").responseJSON { response in
print(response.result) // result of response serialization

if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
}

我从 API 请求中得到以下响应:

JSON: {
base = stations;
clouds = {
all = 0;
};
cod = 200;
coord = {
lat = "51.51";
lon = "-0.13";
};
dt = 1485031800;
id = 2643743;
main = {
humidity = 83;
pressure = 1026;
temp = "270.54";
"temp_max" = "273.15";
"temp_min" = "267.15";
};
name = London;
sys = {
country = GB;
id = 5091;
message = "0.0038";
sunrise = 1484985141;
sunset = 1485016345;
type = 1;
};
visibility = 7000;
weather = (
{
description = haze;
icon = 50n;
id = 721;
main = Haze;
}
);
wind = {
speed = 1;
};
}

我想从这个 JSON 响应中保存天气描述,这样我就可以使用以下语句:

if var currentWeather = sunny {
return "Nice day!"
} else {
return "Uh-Oh, keep warm!"
}

如果有人能帮我解决这个问题,我将不胜感激!如果我必须使用 SwiftyJSON 来让它更容易,那很好,我已经为此苦苦挣扎了一段时间,需要弄清楚!

最佳答案

您可以在打印输出 JSON 响应后解析结果:

guard let JSON = response.result.value as? [String:Any],
let weather = JSON["weather"] as? [[String:Any]] else {
print("Could not parse weather values")
return
}

for element in weather {
if let description = element["description"] as? String {
print(description)
}
}

如果你想保存结果,或者根据你描述的某个结果做一些事情,你可以插入其他东西而不是像 print(description) 一样:

if description == "sunny" {
//do something
}

让我知道这是否有意义。请记住,Xcode 控制台中的 () 表示“数组”。

关于ios - 将 Alamofire 结果保存为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41784855/

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