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!
Creating a thread in Swift is pretty simple using Thread class. You can either specify objc function through selector as a starting point, or pass a closure, and, more convenient way, subclass Thread . Thread is not started when the initializer is called. You need to call start() method explicitly to start the tread.
Threads are especially useful when you need to perform a lengthy task, but don't want it to block the execution of the rest of the application. In particular, you can use threads to avoid blocking the main thread of the application, which handles user interface and event-related actions.
A dispatch queue that is bound to the app's main thread and executes tasks serially on that thread. A dispatch queue that executes tasks concurrently using threads from the global thread pool. A dispatch queue that executes tasks serially in first-in, first-out (FIFO) order.
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)!) } }) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With