ios - 显示我从 JSON 获得的数据

标签 ios json swift uicollectionview

我有一个来自 Darksky APIJSON 调用,我得到了 JSON 和我需要的数据。 问题是,我无法真正弄清楚如何显示从 API 获得的 temperature 示例。 我有一个天气结构,我在其中进行 JSON 调用,这是天气结构:

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 中?)以及如何显示数据。

提前致谢!

最佳答案

在你的 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
}

关于ios - 显示我从 JSON 获得的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53674913/

相关文章:

iphone - 用于 iOS 项目的 XMLRPC-iOS

ios - 线程 8 : Signal SIGABRT When performing a segue

ios - 标签栏显示警报消息

javascript - 如何迭代 JSON 以使用动态数据制作 ejs 片段

ios - 如何合并两个仅包含唯一值的字典

ios - 选择后 UITableViewCell 内容发生变化

php - Laravel Eloquent 对象,长文本被截断

javascript - 从 JSON 中填充两个选择

ios - 无法使用 tapGestureRecognizer 在屏幕上注册点击

ios - 如何将自定义单元格连接到 UIViewController?