James Stonehill James Stonehill - 18 days ago 7
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

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
            completion?(result)
        }
    }
}

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

Usage:

doSomethingTimeConsuming { result in
    //this closure will be called when your time consuming function completes execution
}
Comments