我有一个函数是这样的:
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上运行它。
我尝试过Swift2的GDC方法,但它不起作用。
Swift3中的线程主题有什么变化吗?
谢谢!
发布于 2016-10-06 20:02:21
可以在后台加载图像,但不能在后台线程上执行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)!)
}
})
}
}发布于 2018-04-12 14:12:32
Swift 4.0
函数图像(url: URL) { var setupImageViewWithURL: 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 =图像self.imageImageView.frame = CGRect(x: 0,y: 0,width: UIScreen.main.bounds.size.width,height:(image?.size.height)!) }
发布于 2018-01-06 03:28:28
DispatchQueue.global(qos:.background).async {
}
https://stackoverflow.com/questions/39894834
复制相似问题