Run a background thread on Swift 3
33,472
Solution 1
It's OK to load image on the background, but it's not OK to perform UI updates on background thread. 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)!)
}
})
}
}
Solution 2
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)!) } } } }
Related videos on Youtube
Author by
FS.O6
Updated on September 29, 2020Comments
-
FS.O6 over 3 years
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
.I've tried the
GDC
methods ofSwift2
, but it didn't work.Did anything change in the thread topic in
Swift3
?Thank you!
-
Sachin Vas over 7 years
-
FS.O6 over 7 years@New16 I've already tried it, it doesn't even complies
-
Martin R over 7 yearsPossible duplicate of How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3?.
-
Sachin Vas over 7 years@FS.O6 I am using it in my code. I don't know the way you are implementing it. Show what error you are getting.
-
Max Pevsner over 7 yearsYou don't want to run it on background thread. UI updates should be never performed on background threads.
-
FS.O6 over 7 years@MaxPevsner I want to load the image on the background because it's very slow now
-
Max Pevsner over 7 years@FS.O6, see my answer below.
-
-
FS.O6 over 7 years
ImageWithImage
is a method that crops the image, can it be done on a background thread? -
Max Pevsner over 7 years@FS.O6, I don't think it should be problem. You can test it.
-
FS.O6 over 7 yearsOk, great. Thanks!
-
HMD about 6 yearsWhat is this answer add to the already accepted answer? To me it's just a copy-paste with minimal change.