Swift 2.x
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let image = self.loadImage()
// 回到主线程更新UI
dispatch_async(dispatch_get_main_queue()) {
self.imageView.image = image
}
}dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
print("test")
}Swift 4.0
DispatchQueue.global(qos: .userInitiated).async {
let image = self.loadImage()
// back to the main thread
DispatchQueue.main.async {
self.imageView.image = image
}
}DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
print("Are we there yet?")
}
本文介绍了在Swift中如何使用异步任务加载图片,并确保UI更新在主线程进行。通过不同版本Swift代码示例展示了dispatch_async及DispatchQueue的用法。
1515

被折叠的 条评论
为什么被折叠?



