问题
Im trying to hide a element using swift 3. The element won't hide if its in session.dataTask, but if I move it outside session.dataTask the element hides fine. Is it possible to hide a element in session.dataTask?
@IBOutlet weak var login_box: UIStackView!
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
//Following won't hide element
self.login_box.isHidden = true
}
//If placed here element hides fine
login_box.isHidden = true
task.resume()
回答1:
First of all you need to start URLSessionDataTask instance using resume and always perform UI changes on main thread.
let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
DispatchQueue.main.async {
self.login_box.isHidden = true
}
}
task.resume()
It will take some time get response from server (depends on your internet speed), but if error is not nil then it will not hide your login_box because it is return from the block.
来源:https://stackoverflow.com/questions/41478673/swift-3-hide-elements