在成功的JSON请求中,我希望更改我界面中某些按钮的可见性。但是,当我按照下面描述的方式处理它时,由于某种原因我遇到了巨大的滞后。打印声明在每个状态调用中都会显示,但按钮本身的可见性不会发生变化,甚至最多30秒。
func buttonStateOne() {
self.executeButton.isHidden = false
self.clearButton.isHidden = false
self.stopButton.isHidden = true
self.greyExecuteButton.isHidden = true
self.greyClearButton.isHidden = true
self.greyStopButton.isHidden = false
self.drawUIView.isUserInteractionEnabled = true
print("On state one")
}
func buttonStateTwo() {
self.executeButton.isHidden = true
self.clearButton.isHidden = true
self.stopButton.isHidden = true
self.greyExecuteButton.isHidden = false
self.greyClearButton.isHidden = false
self.greyStopButton.isHidden = false
self.drawUIView.isUserInteractionEnabled = false
print("On state two")
}
func buttonStateThree() {
self.executeButton.isHidden = true
self.clearButton.isHidden = true
self.stopButton.isHidden = false
self.greyExecuteButton.isHidden = false
self.greyClearButton.isHidden = false
self.greyStopButton.isHidden = true
self.drawUIView.isUserInteractionEnabled = false
print("on state three")
}
@IBAction func sendLines() {
self.buttonStateTwo()
// Draw a path
let theDrawView: DrawView = drawView as! DrawView
var pathPoints = [Any]()
for line in theDrawView.lines {
pathPoints.append([line.start.x, line.start.y])
}
// Send the path
let json: [String: Any] = [ "path": pathPoints ]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var request = URLRequest(url: URL(string: "http://localhost:5000/path")!)
request.httpMethod = "POST"
request.httpBody = jsonData
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
var responseString: String = ""
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: String] {
print(responseJSON["status"]!)
responseString = responseJSON["status"]!
}
if responseString == "SUCCESS" {
self.buttonStateThree()
} else {
self.buttonStateOne()
}
}
task.resume()
}
答案 0 :(得分:1)
必须在主线程上更新UI,因此将包含buttonState...
方法的块分派给主线程:
DispatchQueue.main.async {
if responseString == "SUCCESS" {
self.buttonStateThree()
} else {
self.buttonStateOne()
}
}