我不知道为什么我无法在我的UILabel中打印“pocetDatabaze3”。
这是我的代码:
@IBOutlet weak var aktualniPocet: UILabel!
var pocetDatabaze2 = 0
var pocetDatabaze3 = "dfh"
override func viewDidLoad() {
super.viewDidLoad()
if let url = NSURL(string: "http://servis.dronysitmp.cz/cteni_baterie.php") {
let task = URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
//print(data)
if let pocetDatabaze = NSString(data: data!, encoding: String.Encoding.ascii.rawValue){
self.pocetDatabaze2 = Int(pocetDatabaze as String)!
//self.pocetDatabaze3 = String(describing: pocetDatabaze)
}
}
);
task.resume()
}
pocetDatabaze3 = String(pocetDatabaze2 as Int)
aktualniPocet.text = pocetDatabaze3
}
在UILabel中它显示“0”但它应该是“25”。加载此视图后,我还有两个操作。当我使用它们时,它会显示正确的值。其余的是:
@IBAction func odecteni(_ sender: UIButton) {
pocetDatabaze2 = pocetDatabaze2 - 1
self.pocetDatabaze3 = String(pocetDatabaze2 as Int)
aktualniPocet.text = pocetDatabaze3
}
答案 0 :(得分:3)
这是一个线程问题。 URLSession
是异步的,因此您必须更新completionHandler
。
let task = URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
//print(data)
if let pocetDatabaze = NSString(data: data!, encoding: String.Encoding.ascii.rawValue) {
self.pocetDatabaze2 = Int(pocetDatabaze as String)!
self.pocetDatabaze3 = String(pocetDatabaze2 as Int)
DispatchQueue.main.async {
self.aktualniPocet.text = pocetDatabaze3
}
}
})
您需要调用DispatchQueue.main
,因为您应该更新主线程中的UI。然后你可以注释掉其他两个电话。
答案 1 :(得分:0)
做这样的事情
if let url = NSURL(string: "http://servis.dronysitmp.cz/cteni_baterie.php") {
let task = URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
if let pocetDatabaze = NSString(data: data!, encoding: String.Encoding.ascii.rawValue){
DispatchQueue.main.async {
self.aktualniPocet.text = pocetDatabaze as! String
}
}
}
);
task.resume()
}
答案 2 :(得分:-2)
您应该只从主线程更新UI。
if let url = NSURL(string: "http://servis.dronysitmp.cz/cteni_baterie.php") {
let task = URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
//This block executes on a background thread
if let pocetDatabaze = NSString(data: data!, encoding: String.Encoding.ascii.rawValue){
DispatchQueue.main.async{ // Add this to your code
// This block executes on the Main Thread and the UI updates properly
self.pocetDatabaze2 = Int(pocetDatabaze as String)!
}
}
}
);
task.resume()
}
有关Swift中多线程和GCD的更多信息,您可以阅读以下文章: https://developer.apple.com/documentation/dispatch
https://www.raywenderlich.com/148513/grand-central-dispatch-tutorial-swift-3-part-1