James Stonehill James Stonehill - 1 year ago 66
iOS Question

How do you wait for the correct result of a method call?

I've got a method that, due to the computational load of the problem, sometimes takes several seconds to return the result. Note that this is purely an 'offline' issue and the function makes no calls to web based APIs.

Currently, whenever I ask for the return of the method it just returns nil as it is still working on the function on another thread.

How can I write a function that waits for the correct, non-nil response of the function?

Answer Source

You should use GCD to dispatch time consuming block to a background thread. The main thing here is not to block the main thread with hard tasks.

Swift 3 example:

func doSomethingTimeConsuming(completion: ((Any)->Void)?) {
    DispatchQueue.global(qos: .background).async {
        //do time consuming task in here (background thread)
        //let result = ...
        DispatchQueue.main.async {
            //use callback here (main thread)
            //let's assume the result of your calculation is some object or struct

Replace Any with actual result type you expect from your function.


doSomethingTimeConsuming { result in
    //this closure will be called when your time consuming function completes execution
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download