27

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 of Swift2, but it didn't work.

Did anything change in the thread topic in Swift3?

Thank you!

jamryu
  • 668
  • 10
  • 24
FS.O6
  • 1,394
  • 2
  • 20
  • 42

3 Answers3

59

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)!)
            }
        })
    }
}
Max Pevsner
  • 4,098
  • 2
  • 18
  • 32
5

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)!)
            }
        }
    }
}
Prateek kumar
  • 244
  • 3
  • 9
  • 2
    What is this answer add to the already accepted answer? To me it's just a copy-paste with minimal change. – HMD Apr 12 '18 at 06:32
0

DispatchQueue.global(qos: .background).async {

}

Aditya Sharma
  • 585
  • 5
  • 18