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.
DispatchQueue
s 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.
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