Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running code from a specific thread in Swift

I have a function like this:

func foobar() {
  let targetThread = Thread.current

  DispatchQueue.main.async {
    UIView.animate(withDuration: 0.5, animations: {
      // Code I need to run on the main thread
    }, completion: {
      // Code I want to run on targetThread -- HOW?
    }
  }
}

How do I execute code from targetThread? Thanks.

like image 519
7ball Avatar asked Mar 07 '17 19:03

7ball


1 Answers

DispatchQueues are not threads. You'll note there is no way to get the current DispatchQueue the way you can get the current thread. If you just want to run code somewhere that isn't the main thread, you can use:

DispatchQueue.global().async { ... }

If you really want to target your specific thread, you have two choices.

The first is you can use NSObject's perform(_:on:with:waitUntilDone:) (or one of the related methods) and pass the NSThread you've gotten. There isn't enough context in your question to say if this will work for you or to give an example, but you can search.

The second is to re-work your code that is starting all of this to use an NSOperationQueue, so foobar() would be run in an operation on the NSOperationQueue and then in your completion for the animation, you'd schedule another NSOperation to run on the same Operation Queue. You could also do this using dispatch queues directly: i.e. create your own dispatch queue, dispatch foobar, then dispatch back to your queue from main when the animation completes.

like image 73
i_am_jorf Avatar answered Oct 12 '22 11:10

i_am_jorf