简体   繁体   中英

Swift 4 UI stuck after getting json response

I am developing an application in Swift 4 and facing issue with json parsing. Everything is working fine with data and values but when i get data from json response and display in UI, UI is stuck for some seconds until i move UI screen or click textfield. Sometimes its working fine but mostly its stuck until i do clicks on UI.

My code is :

LoadCountries { jsonString in
    self.startAnimating()
    DispatchQueue.main.async {
        self.stopAnimating()
        print(jsonString)
    }
}

func LoadCountries(completion:  @escaping ([Countries]) -> ()) {
    guard let url = URL(string: "https://www.adsfasdf.com/api/countries") else {return}
    URLSession.shared.dataTask(with: url) { (data, response, err) in
        do {
            let jsonString = try JSONDecoder().decode([Countries].self, from: data!)
            completion(jsonString)
        } catch let jsonErr {
            print("Error serializing json:", jsonErr)
        }
    }.resume()
}

Here is corrected version, also please handle TODOs and weakselfs...

loadCountries { jsonString in
    DispatchQueue.main.async {
        self.stopAnimating()
        print(jsonString)
    }
}

func loadCountries(completion: @escaping ([Countries]) -> ()) {
    // Note:assumes that loadCountries(...) is called on mainthread
    self.startAnimating()

    guard let url = URL(string: "https://www.adsfasdf.com/api/countries") else {
        // TODO:completion block not called?
        return
    }
    URLSession.shared.dataTask(with: url) { (data, response, err) in
        do {
            // TODO: crash if data is nil
            let jsonString = try JSONDecoder().decode([Countries].self, from: data!)
            completion(jsonString)
        } catch let jsonErr {
            // TODO:completion block not called?
            print("Error serializing json:", jsonErr)
        }
    }.resume()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM