我有一个像这样的功能:
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)!)
}
我想在Background
thread
上运行它。
我已经尝试了GDC
Swift2
方法,但它没有用。
Swift3
中的主题话题是否有任何变化?
谢谢!
答案 0 :(得分:58)
可以在后台加载图片,但在后台线程上执行UI更新并不行。这就是函数必须包含两个线程的原因。
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)!)
}
})
}
}
答案 1 :(得分:3)
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)!) } } } }
答案 2 :(得分:0)
DispatchQueue.global(qos:.background).async {
}