Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a background thread on Swift 3

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!

like image 490
FS.O6 Avatar asked Oct 06 '16 11:10

FS.O6


People also ask

How do I run a thread in Swift?

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.

What is thread in Swift?

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.

What is the use of DispatchQueue in Swift?

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.


1 Answers

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)!)             }         })     } } 
like image 136
Max Pevsner Avatar answered Sep 21 '22 12:09

Max Pevsner