如何从URL解析Json并在Xcode的Collection视图中显示

问题描述 投票:0回答:1

这里是我要解析的Api代码示例

     {"@iot.nextLink" : "Google.com","value" : [ {
    "phenomenonTime" : "2020-02-12T01:38:17.622Z",
    "resultTime" : "2020-02-12T01:38:17.622Z",
    "result" : 1009.3,
    "Datastream@1" : "Yahoo.com",
    "FeatureOfInterest@2" : "bing.com",
    "@iot.id" : 4093015,
    "@iot.selfLink" : "youtube.com"},

    {"phenomenonTime" : "2020-02-12T01:23:11.397Z",
    "resultTime" : "2020-02-12T01:23:11.397Z",
    "result" : 1009.7,
    "Datastream@1" : "walmart.com",
    "FeatureOfInterest@2" : "bestbuy.com",
    "@iot.id" : 4092867,
    "@iot.selfLink" : "gmail.com"}, ...]}

我创建了用于解析Json的结构

struct Initial: Decodable {
let value : [Blue]}

struct Blue: Decodable {
let phenomenonTime : String
let result : Double}

我只想显示PhenomenonTime值和结果值。接下来,我做了

      var url1 = ""

      override func viewDidLoad() {
      let url = URL(string: url1)
      URLSession.shared.dataTask(with: url!) { (data, response, error) in
        guard let data = data else { return }
                do {
             let initial = try? JSONDecoder().decode(Initial.self, from: data)
                    print(initial?.value)

             }catch {
            print("Error")
        }

    }.resume()
}

[这是我解析JSON的代码。我可以打印值

Optional([GTSeaLevelAPP.Blue(phenomenonTime: "2020-02-12T01:38:17.622Z", result: 1009.3),
GTSeaLevelAPP.Blue(phenomenonTime: "2020-02-12T01:23:11.397Z", result: 1009.7),...])

但是,当我尝试这样做时,它不允许我

print(initial?.value.result)

出现一个错误,说“类型[[Blue]'的值没有成员'结果'”。因此,我不知道该如何解决只打印值或现象时间的问题,因此我只能将值放入集合视图中,或仅将现象时间放在另一个集合视图中。另外,我不知道如何解析Json,以便收集视图可以看到justenceTime的数组。

extension ViewController:UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 100
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = pressureView.dequeueReusableCell(withReuseIdentifier: "check", for: indexPath) as? PressureCollectionViewCell

    cell?.number.text=String(indexPath.row)
    return cell!
}

[目前,我做到了,所以它将在每个单元格中显示一个不同的数字,但我不知道如何将所有值都放入一个数组中,并将所有hospectTime放入一个数组中,并将它们呈现给collectionview。当我尝试引用以使单元格文本显示值时

        cell?.number.text=initial?.value[indexPath.row]

它说:

“使用未解析的标识符'initial'”

所以,要怎么解决?

json xcode parsing url uicollectionview
1个回答
0
投票

因此,将您的viewcontroller设置为:

class ViewController: UIViewController {

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = .lightGray
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()

    var url1 = "your_url"
    private var cellId: String = "12312"
    private var phenomenonTimeArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(self.collectionView)
        NSLayoutConstraint.activate([
            self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
            self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
        ])
        self.collectionView.register(PressureCollectionViewCell.self, forCellWithReuseIdentifier: self.cellId)
        self.getDataFromServer()
    }

    func getDataFromServer() {
        let url = URL(string: url1)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            guard let data = data else { return }
            do {
                let initial = try? JSONDecoder().decode(Initial.self, from: data)
                if let value = initial?.value {
                    self.phenomenonTimeArray = value.map { (blue) -> String in
                        return blue.phenomenonTime
                    }
                    self.collectionView.reloadData()
                }
            } catch {
                print("Error")
            }
        }.resume()
    }
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.phenomenonTimeArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellId, for: indexPath) as! PressureCollectionViewCell
        cell.item = phenomenonTimeArray[indexPath.row]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return .init(width: collectionView.frame.width, height: 30)
    }
}

和您的单元格(根据要求设计单元格:]

class PressureCollectionViewCell: UICollectionViewCell {

    var item: String? {
        didSet {
            self.label.text = item
        }
    }

    private lazy var label: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError()
    }

    private func setupViews() {
        self.addSubview(self.label)
        NSLayoutConstraint.activate([
            self.label.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            self.label.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            self.label.topAnchor.constraint(equalTo: self.topAnchor),
            self.label.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ])
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.