我尝试使用服务器响应更新label.text。但只有在第二次调用方法后才更新标签。有什么问题?
不推荐使用dispatch_async(dispatch_get_main_queue())。我将其更改为DispatchQueue.main.async,但它不起作用。
swift 2的示例: Swift changing text of a label after downloading content of a web page
不工作代码:
@IBAction func buttonAction(_ sender: Any) {
let url = URL(string: "https://api.nasa.gov/planetary/apod?date=2005-2-22&api_key=DEMO_KEY")!
let task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
if let data = data,
let stringData = String(data: data, encoding: .utf8) {
print("stringData: \(stringData)") // prints every time
DispatchQueue.main.async {
// change label text after second calling.
// ??? How to change label text at first calling ???
self?.mainLabel.text = stringData
}
}
}
task.resume()
}
答案 0 :(得分:1)
试试这个
import { zip } from 'rxjs/observable/zip'
在buttonAction中写下以下代码
var labelString : String = "" {
didSet {
self.mainLabel.text = labelString
}
}