Question: How to update UI using the JSON result through a completion handler?


How to update UI using the JSON result through a completion handler?

Answers 1
Added at 2017-01-01 00:01

I'm trying to update some labels based on data returned from JSON. Here are the data objects and the function to update the JSON data objects :

class sampleJSON {

  var airbnbUS: Int?
  var airbnbLocal: Int?

  init(airbnbUS: Int, airbnbLocal: Int?) {
    self.airbnbUS = airbnbUS
    self.airbnbLocal = airbnbLocal

  //Used to download data to local objects using the network service manager
  static func downloadAllData(urlExtension: String, completionHandler: @escaping (sampleJSON?) -> ()) {

    let usm = UrlSessionNetworkManager.sharedManager

    if let jsonDictionary = usm.parseJSONFromData(urlExtension:"\(urlExtension)")

      if let resultsDictionary = jsonDictionary["result"] as? [[String : Any]]?{
        let costDictionary = resultsDictionary?[0]
        let cost = costDictionary?["cost"] as? [String: Any]

        if let airbnb = cost?["airbnb_median"] as? [String: AnyObject]{
            let airbnbUS = airbnb["USD"] as! Int
            let airbnbLocal = airbnb["CHF"] as! Int

         sampleJSON(airbnbUS: airbnbUS, airbnbLocal: airbnbLocal)
    } else {
      print("Error: Cannot retrieve JSON Data")

Here is where I'm trying to update UI:

var JSON: sampleJSON?

 override func viewDidLoad() {

       sampleJSON.downloadAllData(urlExtension:"cities/basel-switzerland",completionHandler: {_ in

  DispatchQueue.main.async(execute: {
  self.topLabel.text = String(describing: self.JSON?.airbnbUS)
  self.lowerLabel.text = String(describing: self.JSON?.airbnbLocal)

As of right now when the viewDidload is called the labels are blank, I tried adding a self.view.setNeedsDisplay() to the end of the completion block but the labels still remain blank. EDIT: I noticed if I put a breakpoint inside the completion block in the viewDidLoad it's not called.

Answers to

How to update UI using the JSON result through a completion handler?

nr: #1 dodano: 2017-01-01 01:01

You never call your completion handler within downloadAllData so its closure will never execute to set your labels.

In place of this line where you create a sampleJSON and do nothing with it:

sampleJSON(airbnbUS: airbnbUS, airbnbLocal: airbnbLocal)

return sampleJSON within completionHandler:

completionHandler(sampleJSON(airbnbUS: airbnbUS, airbnbLocal: airbnbLocal))
Source Show
◀ Wstecz