Swift: 在 URLSessionTask 中设置标签的文本

Swift: Setting the text of a label in a URLSessionTask

所以我正在使用 URLRequest() 下载 JSON 文件。 我解析它以获得特定的字符串,并且我想将 ViewController 中的标签文本设置为该特定字符串。 我使用 CompletionHandler 来检索从另一个 Swift 文件获取 JSON 文件的函数。

调用函数和设置标签的代码如下:

class SecondViewController: UIViewController {
    tr = TransportServices()
    tr.getLyftData(origin: originstring, destination: destinationstring){ json in
     //Parsing JSON in order to get specific data
        self.lyftlabel.text = stringexample
    }
}

这是获取 JSON

的代码
func getLyftData(origin: String, destination: String, completionHandler: @escaping ([String: Any]) -> ()){


    let urlrequest = URLRequest(url: URL(string: urlstring)!)


    let config = URLSessionConfiguration.default
    let sessions = URLSession(configuration: config)

    let task = sessions.dataTask(with: urlrequest) {(data, response, error) in
        guard error == nil else {
            print(error!)
            return
        }
        guard let responseData = data else {
            print("error, did not receive data")
            return
        }
        do {
            if let json = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any]{
                completionHandler(json)
            }
        }
        catch {
            print("Error with URL Request")
        }
    }
    task.resume()
}

这可以完成工作,但速度非常慢。我知道存在运行时问题,因为 UILabel.text 必须仅从主线程设置,但我不知道任何其他修复方法。请帮忙。

如果你想在主线程中设置标签文本,使用这个:

DispatchQueue.main.async {

self.lyftlabel.text = stringexample

}