【问题标题】:Save Alamofire Result as Variable?将 Alamofire 结果保存为变量?
【发布时间】:2017-01-21 21:42:52
【问题描述】:

我一直在尝试找出如何将来自 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 来简化它,那很好,我已经为此苦苦挣扎了一段时间,需要弄清楚!

【问题讨论】:

    标签: ios swift xcode swift3 alamofire


    【解决方案1】:

    您可以在打印出 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 控制台中的() 表示“数组”。

    【讨论】:

    • 感谢您的仓促回复,等 Xcode 完成更新后会试一试!我了解它的大部分工作原理,希望我能开始了解如何自己做到这一点。
    • 态度好。如果您遇到问题,请告诉我@Miles
    • 我尝试了此代码,但我在let weather = JSON["weather"] as? [[String:Any]] else { 行收到Type Any has no subscript members 我也尝试将其更改为 AnyObject 但仍然出现相同的错误。
    • 哦,对了。你会想投response.result.value as? [String:Any]@Miles
    • 太棒了,完美运行。非常感谢您!
    猜你喜欢
    • 2016-06-29
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2016-04-18
    • 2021-10-25
    • 2021-03-01
    相关资源
    最近更新 更多