【发布时间】:2019-01-28 16:11:18
【问题描述】:
在我提出请求并找到并填充我的对象之前,我无法更改视图。
我试图将我的代码与 GCD 异步。这不工作
override func viewDidLoad() {
getHeartStroke()
NotificationCenter.default.addObserver(forName:NSNotification.Name("HeartStrokeNotification"), object: nil, queue: nil, using: notificationFinish)
}
func getHeartStroke() {
AF.request("http://localhost:8080/heartstroke", method: .get, headers: nil).responseJSON(completionHandler: {response in
if (response.error == nil)
{
let json = JSON(response.result.value!)
DispatchQueue.global(qos: .userInitiated).async {
guard let hearstrokeArray = try? JSONDecoder().decode([HeartStroke].self, from: json.rawData()) else{
debugPrint("An error has occurred")
return
}
NotificationCenter.default.post(name:NSNotification.Name("HeartStrokeNotification"), object: hearstrokeArray, userInfo: nil)
}
}else{
NotificationCenter.default.post(name:NSNotification.Name("HeartStrokeErrorNotification"), object: nil, userInfo: nil)
}
})
}
func notificationFinish(notification:Notification) -> Void{
if (notification.name.rawValue == "HeartStrokeNotification"){
arrayHeartstroke = notification.object as! [HeartStroke]
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
使用此代码,我会一直阻塞在我的页面上,直到 getHeartStroke() 结束,我希望在获取的同时在我的应用程序中导航。
【问题讨论】:
-
AF里面有什么代码???
-
你为什么在这里使用通知?只需使用完成处理程序。
-
您还应该在 viewDidLoad() 方法中调用 super.viewDidLoad()。
标签: swift grand-central-dispatch codable