Swift:在URLSessionTask中设置标签文本
因此,我正在使用URLRequest()下载一个JSON文件。 我解析它是为了得到一个特定的字符串,我想将ViewController中标签的文本设置为该特定字符串。 我使用CompletionHandler来检索从另一个Swift文件获取JSON文件的函数 下面是调用函数和设置标签的代码:Swift:在URLSessionTask中设置标签文本,swift,uilabel,urlsession,Swift,Uilabel,Urlsession,因此,我正在使用URLRequest()下载一个JSON文件。 我解析它是为了得到一个特定的字符串,我想将ViewController中标签的文本设置为该特定字符串。 我使用CompletionHandler来检索从另一个Swift文件获取JSON文件的函数 下面是调用函数和设置标签的代码: class SecondViewController: UIViewController { tr = TransportServices() tr.getLyftData(origin:
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
}
谢谢,我在哪里调用此函数?只需将其替换为
self.lyftlabel.text=stringexample
line即可