快速显示JSON数据到插座

时间:2019-02-26 07:25:40

标签: ios json swift jsonparser

我对编码非常陌生,正尝试一次一步学到东西。我搜索了一个堆栈,发现了一些很棒的主意,但没有任何答案可以回答我希望学习的内容。

我创建了一些代码,可以从单个Web URL中提取JSON天气数据。它仅共享单个位置的天气数据,不请求信息。

我能够打印JSON数据中的信息! (这是一个巨大的步骤)。下一步是在我的应用程序和手机上显示来自JSON数据的信息。我在表格视图中发现了很多有关此操作的文章,但未能使它适用于我的应用程序,主要是因为其中许多文章都要求您搜索位置以提取数据(不适用于我的情况) )。

我想从JSON数据中获取一条信息并将其显示在屏幕上。

我在情节提要中创建了一个标签,并将其连接到视图控制器。

我也有weather.swift来调用JSON数据。

我遇到的问题是我收到错误“类型'[天气]'的值没有成员'名称'”。这是在我的view controller.sift中的代码行“ locationOutlet.text = observationsData.name”上。

这是我的视图控制器中的代码:

导入UIKit

ViewController类:UIViewController {

@IBOutlet weak var locationOutlet: UILabel!

var observationsData = [Weather]()


override func viewDidLoad() {
    super.viewDidLoad()

   /* Weather.observations(withLocation: ",") { (results:[Weather]) in
        for result in results {
                print("\(result)\n\n")
        }
       */

    }

// Do any additional setup after loading the view, typically from a nib.

    func loadweatherData (location:String) {

        Weather.observations(withLocation: ",") { (results:[Weather]?) in
                if let weatherData = results {
                    self.observationsData = weatherData
            }

            //let weatherObject = observationsData[IndexPath.row]

    }

    func displayweatherData (location:String) {

        locationOutlet.text = observationsData.name

    }
    //locationOutlet?.text = observationsData.name

}

}

这是weather.swift中的代码,该代码调用JSON数据。

import Foundation

struct Weather {
    let name:String
    let air_temp:Double
    let wind_spd_kt:Double
    let swell_height:Double


    enum SerializationError:Error {
        case missing(String)
        case invalid(String, Any)
    }

init(json:[String:Any]) throws {
    guard let name = json["name"] as? String else{throw SerializationError.missing("Name is missing")}

    guard let air_temp = json["air_temp"] as? Double else{throw SerializationError.missing("Air temp is missing")}

    guard let wind_spd_kt = json["wind_spd_kt"] as? Double else{throw SerializationError.missing("Wind speed is missing")}

    guard let swell_height = json["swell_height"] as? Double else{throw SerializationError.missing("Swell hight is missing")}

    self.name = name
    self.air_temp = air_temp
    self.wind_spd_kt = wind_spd_kt
    self.swell_height = swell_height
}

static let basePath = "http://www.bom.gov.au/fwo/IDN60701/IDN60701.94937.json"

static func observations (withLocation location:String, completion: @escaping ([Weather]) -> ()) {

    let url = basePath //+ location
    let request = URLRequest(url: URL(string: url)!)

    let task = URLSession.shared.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in

    var observationsArray:[Weather] = []

    if let data = data {

    do {
        if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
            if let currentObservations = json["observations"] as? [String:Any] {
                if let currentData = currentObservations["data"] as? [[String:Any]] {
                    for dataPoint in currentData {
                        if let weatherObject = try? Weather(json: dataPoint) {
                            observationsArray.append(weatherObject)
                                        }
                                    }
                                }
                            }
                        }
    }catch{
        print(error.localizedDescription)
    }

    completion(observationsArray)

    }
}

task.resume()
}

}

很显然,我正在学习并尝试做一些可能比我真正想的要难的事情。我如何获得标签以显示数据的任何帮助都非常好。谢谢您的宝贵时间!

2 个答案:

答案 0 :(得分:3)

然后您要做的就是获取第一个索引的天气对象并将其属性显示在标签中。

Weather.observations(withLocation: ",") { (results) in
    if let firstIndexWeatherData = results.first {
        //As API calls are usually on background thread and Apple requires Main Thread to update the UI so set your weatherData name to label on main thread like this.
        DispatchQueue.main.async {
            self.locationOutlet.text = firstIndexWeatherData.name
        }
    }
}

答案 1 :(得分:0)

您正在尝试访问数组[Weather].name 相反,您可能想访问Weather.name

尝试访问数组中的一个Weather对象