将Alamofire结果保存为变量?

编程入门 行业动态 更新时间:2024-10-24 06:35:43
本文介绍了将Alamofire结果保存为变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在尝试找出如何将Alamofire的JSON响应的一部分另存为变量以创建if语句,而且似乎找不到解决方法。

I've been trying to find out how to save a part of a JSON response from Alamofire as a variable to make an if statement and can't seem to find how to do it.

我编写了一段代码作为示例,该问题包括以下内容:

I made a piece of code to use as an example for the question which consists of the following:

import UIKit import Alamofire class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() Alamofire.request("api.openweathermap/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响应中,我想保存天气说明,以便可以使用以下语句:

From this JSON response I would like to save the weather description so I could use the following statement:

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

如果有人可以帮助我,我将不胜感激!如果我必须使用SwiftyJSON来简化它,那很好,我已经为此苦苦挣扎了一段时间,需要弄清楚!

If anyone could help me with this I would greatly appreciate it! If I have to use SwiftyJSON to make it easier that's fine I've just been struggling with this for a while and need to figure it out!

推荐答案

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

You can parse your result following the printout of your JSON response:

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 you wanted to save the result, or do something based on a certain result as you described, you could insert something else instead of just print(description) like:

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

让我知道这是否有意义。请记住,在Xcode控制台中,(和)的意思是数组。

Let me know if this makes sense. Keep in mind that ( and ) in the Xcode console means "Array".

更多推荐

将Alamofire结果保存为变量?

本文发布于:2023-05-29 23:11:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355126.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   保存为   Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!