API返回下一个:
{
apparentTemperature = "37.08";
cloudCover = 1;
dewPoint = "31.44";
humidity = "0.8";
icon = cloudy;
ozone = "305.37";
precipIntensity = "0.0023";
precipProbability = "0.06";
precipType = rain;
pressure = "1029.17";
summary = Overcast;
temperature = "37.08";
time = 1450515600;
windBearing = 196;
windSpeed = "2.61";
},
{
apparentTemperature = "39.22";
cloudCover = 1;
dewPoint = "33.13";
humidity = "0.79";
icon = cloudy;
ozone = "304.86";
precipIntensity = "0.0016";
precipProbability = "0.03";
precipType = rain;
pressure = "1029.13";
summary = Overcast;
temperature = "39.22";
time = 1450519200;
windBearing = 203;
windSpeed = "2.76";
},
{
apparentTemperature = "41.17";
cloudCover = 1;
dewPoint = "34.77";
humidity = "0.78";
icon = cloudy;
ozone = "303.99";
precipIntensity = "0.0015";
precipProbability = "0.03";
precipType = rain;
pressure = "1028.96";
summary = Overcast;
temperature = "41.17";
time = 1450522800;
windBearing = 213;
windSpeed = "2.73";
},
{
apparentTemperature = "42.47";
cloudCover = "0.99";
dewPoint = "36.04";
humidity = "0.78";
icon = cloudy;
ozone = "302.97";
precipIntensity = "0.0013";
precipProbability = "0.02";
precipType = rain;
pressure = "1028.82";
summary = Overcast;
temperature = "42.47";
time = 1450526400;
windBearing = 215;
windSpeed = "2.58";
});
icon = "partly-cloudy-day";
summary = "Mostly cloudy starting tomorrow morning.";
};
latitude = "45.745138";
longitude = "21.169898";
offset = 2;
timezone = "Europe/Bucharest";
})
我的代码是:
import UIKit
import Alamofire
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var webView: UIWebView!
@IBOutlet weak var textView: UITextView!
@IBAction func searchWeather(sender: UIButton) {
loadData()
}
func loadData() {
let city: String = textField.text!
let api_key: String = "https://api.forecast.io/forecast/b33607b3d2611f604df5def613283a8a/"
Alamofire.request(.GET, "\(api_key)45.745138,21.169898").responseJSON { response in
print("\(response.result.value)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我想从JSON响应中获取温度,湿度和压力等字段,并将它们放入UItextView到我的应用程序中。我怎样才能获得三个字段?
答案 0 :(得分:2)
这里是湿度的例子(替换"湿度","温度""压力"。另外看看我如何进入你的JSON,使用这个例子知道如何导航并获得你想要的东西
let daily = response.result.value!["daily"] as! NSDictionary
let data = daily["data"] as! NSArray
for obj in data {
print (obj["humidity"])
}
答案 1 :(得分:1)
继续@ hla的回答,应尽可能避免强制展开/演员。如果值为nil /无法生成,它们将导致应用程序崩溃。请使用optional binding来获取此类内容。
正确的实施方式是:
if let daily = response.result.value?["daily"] as? NSDictionary, let data = daily["data"] as? NSArray {
for obj in data {
print (obj["humidity"])
}
}