[英]Run a background thread on Swift 3
I have a function that goes like this: 我有一个像这样的函数:
fileprivate func setupImageViewWithURL(url: URL) {
var image: UIImage? = nil
do {
try image = UIImage(data: Data(contentsOf: url))!
} catch is NSError {
print("Failed")
}
image = self.imageWithImage(sourceImage: image!, scaledToWidth: UIScreen.main.bounds.size.width)
self.imageImageView.image = image
self.imageImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (image?.size.height)!)
}
I want to run it on a Background
thread
. 我想在
Background
thread
上运行它。
I've tried the GDC
methods of Swift2
, but it didn't work. 我已经尝试过
Swift2
的GDC
方法,但它没有用。
Did anything change in the thread topic in Swift3
? Swift3
中的主题主题有什么变化吗?
Thank you! 谢谢!
It's OK to load image on the background, but it's not OK to perform UI updates on background thread. 可以在后台加载图像,但在后台线程上执行UI更新是不行的。 That's why the function must contain two threads.
这就是函数必须包含两个线程的原因。
func setupImageViewWithURL(url: URL) {
var image: UIImage? = nil
DispatchQueue.global().async {
do {
try image = UIImage(data: Data(contentsOf: url))!
} catch {
print("Failed")
}
DispatchQueue.main.async(execute: {
if image != nil {
image = self.imageWithImage(sourceImage: image!, scaledToWidth: UIScreen.main.bounds.size.width)
self.imageImageView.image = image
self.imageImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (image?.size.height)!)
}
})
}
}
Swift 4.0 Swift 4.0
func setupImageViewWithURL(url: URL) { var image: UIImage? = nil DispatchQueue.global(qos: .background).async { do { try image = UIImage(data: Data(contentsOf: url))! } catch { print("Failed") } DispatchQueue.main.async { if image != nil { image = self.imageWithImage(sourceImage: image!, scaledToWidth: UIScreen.main.bounds.size.width) self.imageImageView.image = image self.imageImageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: (image?.size.height)!) } } } }
DispatchQueue.global(qos: .background).async {
DispatchQueue.global(qos:.background).async {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.