【问题标题】:Populating UIComponents With JSON Data使用 JSON 数据填充 UIComponent
【发布时间】:2018-05-30 20:36:34
【问题描述】:

我必须解析并发现一种优雅的方式来处理我的解析数据,并使用它来正确填充 UIElement,例如 UITableViews、UICollectionViews 等。我将在下面发布我的解析方式以及 JSON 文件.

import Foundation

struct Contents : Decodable {

    let data : [Content]
}

struct Content : Decodable {
    let id : Int
    let descricao : String
    let urlImagem : String


}

API 响应文件:

import Foundation


var audioBook = [Content]()


func getAudiobooksAPI() {

        let url = URL(string: "https://alodjinha.herokuapp.com/categoria")

        let session = URLSession.shared

        guard let unwrappedURL = url else { print("Error unwrapping URL"); return }

        let dataTask = session.dataTask(with: unwrappedURL) { (data, response, error) in

            guard let unwrappedDAta = data else { print("Error unwrapping data"); return }

            do {



                     let posts2 = try JSONDecoder().decode(Contents.self, from: unwrappedDAta)
                         audioBook = posts2.data




            } catch {
                print("Could not get API data. \(error), \(error.localizedDescription)")
            }
        }
        dataTask.resume()
    }

TableView 文件:

如何使用我解析的数据进行填充?我真的很难做到这一点。我需要一个解释来指导我如何使用优雅的方式以及作为高级开发人员来做到这一点。

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet var collectionView: UICollectionView!


    override func viewDidLoad() {
        super.viewDidLoad()



        getAudiobooksAPI()




    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {


        return  ?????
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell

               ???????

        return cell

    }
}

JSON:

JSON Model

【问题讨论】:

  • 请删除所有这些空行。你为什么这样做?
  • 你好@meaning-matters!我这样做只是为了你们可能会更好地可视化代码

标签: json swift uitableview


【解决方案1】:

只需使用 completion Handler 更新您的 API 服务

func getAudiobooksAPI(_ completion:@escaping ([Content])->Void) {

        let url = URL(string: "https://alodjinha.herokuapp.com/categoria")

        let session = URLSession.shared

     guard let unwrappedDAta = data else {  completion([Content]());  return}

        let dataTask = session.dataTask(with: unwrappedURL) { (data, response, error) in

            guard let unwrappedDAta = data else { print("Error unwrapping data"); return }

            do {



                let posts2 = try JSONDecoder().decode(Contents.self, from: unwrappedDAta)
                completion(posts2.data)



            } catch {
                print("Could not get API data. \(error), \(error.localizedDescription)")
                completion([Content]())

            }
        }
        dataTask.resume()
    }

这样使用

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet var collectionView: UICollectionView!

     var dataSource: [Content] = [Content]()
    override func viewDidLoad() {
        super.viewDidLoad()



         getAudiobooksAPI { (data) in
            DispatchQueue.main.async {
                self.dataSource = data
                self.collectionView.reloadData()
            }
        }




    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {


        return  self.dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell

             let content = self.dataSource[indexPath.item]

        return cell

    }
}

【讨论】:

  • 太棒了!工作得很好,很干净,哈哈。你不知道你帮了我多少,伙计。
  • 非常感谢!那么,如果我作为高级开发人员在一家公司这样做,我会很好吗?还有其他更清洁的工作方式吗?
  • 是的,上帝,但你必须为 API 制作单独的层,还有很多事情要做,但对于这个目标,是的,完成处理程序工作得很好,
  • 你的意思是像 MVC?
  • 是的架构模式 可以使用 MVVM 的模式
猜你喜欢
  • 2018-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 2018-10-24
  • 2018-12-18
  • 1970-01-01
相关资源
最近更新 更多