如何在视图控制器中使用模型?

时间:2019-05-02 15:47:19

标签: ios swift nsurlsession jsondecoder

我有模型课。我想在视图控制器中使用它,但是我不确定该怎么做。

模型类:

import Foundation

struct Doner:Decodable {
    var doner: [DonerDetails]?
}

struct DonerDetails: Decodable {
    var firstName: String?
    var lastName: String?
    var location: String?
    var mobile: String?
    var age: Int?

    static func fetchDonerData(_ completionHandler: @escaping (Doner) -> ()) {
        let urlString = "any URL"

        URLSession.shared.dataTask(with: URL(string: urlString)!, completionHandler: { (data, response, error) -> Void in
            guard let data = data else { return }

            if let error = error {
                print(error)
                return
            }

            do {
                let decoder = JSONDecoder()
                let donerData = try decoder.decode(Doner.self, from: data)
                print(donerData)

                DispatchQueue.main.async(execute: { () -> Void in
                    completionHandler(donerData)
                })
            } catch let err {
                print(err)
            }
        }) .resume()
    }
}

我的viewcontroller类:

import UIKit

class ViewController: UIViewController {
    var donerData: Doner?
    var donerDetails: [DonerDetails]?

    override func viewDidLoad() {
        super.viewDidLoad()

        DonerDetails.fetchDonerData { (donerData) -> () in
        }
    }
}

我想在视图控制器中调用该模型类以在视图上显示数据,但在执行上述代码后,不会触发模型类。

如何获取名字,姓氏,年龄?

0 个答案:

没有答案