无法从weather-api获得json。 iOS版

时间:2017-01-20 10:56:03

标签: ios iphone json swift xcode

这是JSON文件

if (isset($_POST["submit"])) {

    $ware = $_POST['ware'];
    $wareString = "";
    foreach($ware as $value) {
        $wareString .= $value;
    }
    $warenanzahl = $_POST['warenanzahl'];
    $warenanzahlString = "";
    foreach($warenanzahl as $value1) {
        $warenanzahlString .= $value1;
    }

    $from = 'Form'; 
    $to = 'test@test.de'; 
    $subject = 'Message';

    $body ="Store: Test\n Message:\n $wareString $warenanzahlString";

这是代码。

 {
  "weather":[  
    {  
     "id":804,
     "main":"Clouds",
     "description":"overcast clouds",
     "icon":"04d"
  }
],
 "main":{  
  "temp":273.15,
  "pressure":1035,
  "humidity":84,
  "temp_min":273.15,
  "temp_max":273.15
},

"name":"Wroclaw",

 }

如何从变量weatherDescription中保存json中天气的“主要”或“描述”的值?我尝试在这段代码中,但它没有给我任何东西。 学位和城市名称的工作正确并显示,但天气不起作用。

更新了代码 //////////////////////////////////////

var cityName: String!
var degree: Int!
var someWeather: String!

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]


            if let main = json["main"] as? [String : AnyObject] {
                if let temp = main["temp"] as? Int {
                    self.degree = temp
                }
            }
            if let city = json["name"] as? String {
                self.cityName = city
            }
}

     if let weather = json["weather"] as? [String : AnyObject] {
     if let someWeather = weather["main"] as? String {
     self.weatherDescription = someWeather 
} 
} 

labelWeather.text = self.weatherDescription

以下是所有JSON文件:

  var  let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]


                if let main = json["main"] as? [String : AnyObject] {
                    if let temp = main["temp"] as? Int {
                        self.degree = temp
                    }
                    if let pressuer = main["pressure"] as? Int {
                        self.cisnienie = pressuer
                    }
                }

                if let weather = json["weather"] as? [[String : Any]] {
                    for data in weather {
                        if let main = data["main"] as? String {
                            print(main)
                        }
                    }
                }

                if let nazwa = json["name"] as? String {
                    self.nazwaMiasta = nazwa
                }

1 个答案:

答案 0 :(得分:1)

"天气"是array而非dictionary ..

if let weather = json["weather"] as? [[String : Any]] {
    for data in weather{
       if let main = data["main"] as? String{
           print(main)
       }
    }
}