ios - Swift 3 unclear delay in filling up labels in a collection view -


i reading products data api , print down ids make sure data has been fetched successfully. then, put products titles collection view label.

the strange thing here list of ids printed fast. app wait few seconds till collectionview populated.

i couldn't understand why delay occurring have 10 products, should not take time loading , made loop on them , printed ids in no time!

the following code shows have done yet. hope can me figure out bottle-nick:

import uikit  class testviewcontroller: uiviewcontroller, uicollectionviewdatasource, uicollectionviewdelegate {     @iboutlet weak var collectionview: uicollectionview!      var jsondata : [[string: any]] = [[:]]      override func viewdidload() {         super.viewdidload()          var request = urlrequest(url: url(string: shopurl + "/admin/products.json")!)         request.httpmethod = "get"          urlsession.shared.datatask(with:request, completionhandler: {(data, response, error) in             if error != nil {                 print(error)             } else {                 {                     guard let json = try? jsonserialization.jsonobject(with: data!, options: .allowfragments) as? [string: any] else { return }                      guard let root = json?["products"] as? [[string: any]] else { return }                     self.jsondata = root                     self.collectionview.reloaddata()                      print("this printed fast!")                      product in root {                         guard let id = product["id"] as? int else { return }                         print(id)                     }                 }             }         }).resume()      }      func collectionview(_ collectionview: uicollectionview, numberofitemsinsection section: int) -> int {         return self.jsondata.count     }      func collectionview(_ collectionview: uicollectionview, cellforitemat indexpath: indexpath) -> uicollectionviewcell {         let data = self.jsondata[indexpath.row]          let cell = collectionview.dequeuereusablecell(withreuseidentifier: "testcollectionviewcell", for: indexpath) as!     testcollectionviewcell          if let title = data["title"] as? string {             cell.titlelabel.text = title         }          return cell     } } 

try call reloaddata in main thread:

dispatchqueue.main.async {    self.collectionview.reloaddata() } 

the problem urlsession callback handler still in background thread wont update ui fast, have switch main thread before update ui after call network request urlsession


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -