How do I switch off from the main thread in Swift

Viewed 708

In Swift, if one dispatches a block of work to the main thread using:

DispatchQueue.main.async {
   // work
   // myCallback()
}

Placing print(Thread.current) inside of myCallback indicates that it’s running on the main thread. How do get off the main thread at this point? Or, if I'm looking at this wrong, how can I know when some work I've sent to the main thread is complete?

2 Answers

If you want to make something run on the the background thread manually, you can first get the global system queue with the specified quality-of-service class, then call its async { code } method to schedule a block for execution:

Example:

print(Thread.current)

DispatchQueue.global(qos: .background).async {
    print(Thread.current)
}

Log:

<NSThread: 0x600003b60bc0>{number = 1, name = main}
<NSThread: 0x600003bcf340>{number = 14, name = (null)}

Documentation for Dispatch Queue;

Documentation for global(qos:).

For use another thread you can use the follow.

let queue = DispatchQueue(label: "onde queue")

print(Thread.current)

queue.async {
    print(Thread.current)
    DispatchQueue.main.async {
        print(Thread.current)
    }
}

you have to create one queue, for change of thread, but when you are on another thread and you want to go back to main Thread you will use DispatchQueue.main.async

Related