显示我从JSON获得的数据

时间:2018-12-07 18:17:35

标签: ios json swift uicollectionview

我收到来自Darksky API的{​​{1}}呼叫,我得到了JSON和所需的数据。 问题是,我无法真正弄清楚如何显示例如从API中获得的temperature。 我有一个Weather Struct,可以在其中进行JSON调用,这是Weather Struct:

import UIKit

struct Weather{
    static let basePath: String = "https://api.darksky.net/forecast/MY_API_KEY_IS_HERE/"

    let time: Int
    let icon: String
    let temperature: Double

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

    init(json:[String:Any]) throws{
        guard let time = json["time"] as? Int else {throw SerializationError.missing("Time is missing.")}
        guard let icon = json["icon"] as? String else { throw SerializationError.missing("Icon missing")}
        guard let temperature = json["temperatureMax"] as? Double else {throw SerializationError.missing("temp is missing.")}

        self.time = time
        self.icon = icon
        self.temperature = temperature
    }

    static func forecast(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 forecastArray: [Weather] = []
            if let data = data{
                do{
                    if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]{
                        if let dailyForecast = json["daily"] as? [String:Any]{
                            if let dailyData = dailyForecast["data"] as? [[String:Any]]{
                                for dataPoint in dailyData{
                                    if let weatherObject = try? Weather(json: dataPoint){
                                        forecastArray.append(weatherObject)
                                    }
                                }
                            }
                        }
                    }
                }catch{
                    print(error.localizedDescription)
                }
                completion(forecastArray)
            }
        }
        task.resume()
    }
}

我不知道如何获取其中的数组并将数据放入我的天气单元(这是一个简单的CollectionView单元)中。 这是单元格: 导入UIKit

    class ForecastCell: UICollectionViewCell{


    var mDayLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 14)
        label.textColor = UIColor.white

        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    var mWeatherIcon: UIImageView = {
        let image = UIImageView(image: UIImage(named: "partly-cloudy"))
        image.contentMode = .scaleAspectFit
        image.clipsToBounds = true
        image.translatesAutoresizingMaskIntoConstraints = false
        return image
    }()

    var mTempLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 12)
        label.textColor = UIColor.white

        label.translatesAutoresizingMaskIntoConstraints =  false
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupDayLabel()
        setupTempLabel()
        setupWeatherIcon()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupDayLabel(){
        self.addSubview(mDayLabel)
        mDayLabel.text = "Sunday"

        mDayLabel.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 8).isActive = true
        mDayLabel.centerXAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerXAnchor).isActive = true
    }

    private func setupWeatherIcon(){
        self.addSubview(mWeatherIcon)

        mWeatherIcon.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
        mWeatherIcon.centerYAnchor.constraint(equalTo: contentView.centerYAnchor
).isActive = true
        mWeatherIcon.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 0.8).isActive = true
        mWeatherIcon.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 0.8).isActive = true
    }

    private func setupTempLabel(){
        self.addSubview(mTempLabel)
        mTempLabel.text = "12"

        mTempLabel.centerXAnchor.constraint(equalTo: self.safeAreaLayoutGuide.centerXAnchor).isActive = true
        mTempLabel.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: -8).isActive = true
    }
}

我真的很困惑应该在哪里显示数据(在UIController中?)以及如何处理。

谢谢!

1 个答案:

答案 0 :(得分:1)

在vc里面做

var content = [Weather]() 
Weather.forecast(withLocation:<#loc#>) { (arr) in
 DispatchQueue.main.async {
    content = arr
    self.collectionView.reloadData()
 }
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  return content.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
   let cell = /////// 
   let item = content[indexPath.row] 
   // set cell items here or create configure method in the cell class and pass the model , then set it there 
   return cell
}