[英]Why doesn't my completion block work?
Implementing solution given here How to make a synchronous request using Alamofire?实现这里给出的解决方案如何使用 Alamofire 发出同步请求?
I don't get any errors, it just doesn't work as expected.我没有收到任何错误,只是没有按预期工作。 In tableViewController在 tableViewController 中
override func viewDidLoad() {
super.viewDidLoad()
loadData() { (didCompleteRequest) in
if (didCompleteRequest) {
self.TodosTableView.delegate = self
self.TodosTableView.dataSource = self
print("loading successfull")
} else {
print("loading failed")
}
}
print("leaving viewDidLoad")
}
func loadData(completion: @escaping (Bool) -> Void) {
Alamofire.request(TodosViewController.serverAdress + "projects/index.json").responseJSON { response in
do {
// async stuff
} catch {
completion(false)
}
print("leaving loadData")
completion(true)
}
}
output I get我得到的输出
leaving viewDidLoad离开 viewDidLoad
leaving loadData离开 loadData
loading successfull加载成功
apparently, the first element should be the last one显然,第一个元素应该是最后一个
First viewDidLoad
is running in the main thread.首先viewDidLoad
在主线程中运行。 So when you put this loadData()
in viewDidLoad
controls dispatched to background thread where alamofire works on, and the main thread continues and prints leaving viewDidLoad因此,当您将此loadData()
放在viewDidLoad
控件中时,控件会分派到 alamofire 工作的后台线程,并且主线程继续并打印离开 viewDidLoad
Try this尝试这个
override func viewDidLoad() {
super.viewDidLoad()
self.TodosTableView.delegate = self
self.TodosTableView.dataSource = self
loadData() { (didCompleteRequest) in
if (didCompleteRequest) {
self.TodosTableView.reloadData()
print("loading successfull")
} else {
print("loading failed")
}
}
print("leaving viewDidLoad")
}
You are call block code after get response from server.从服务器获得响应后,您正在调用块代码。 so first call "print("leaving viewDidLoad")".所以首先调用“打印(“离开viewDidLoad”)”。
response code get with delay so call block code with delay响应代码延迟获取所以调用块代码延迟
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.