I basically have to methods, which are being called in my viewDidLoad. The first one gets the user\'s search preferences and saves the preferences to variables at the top. A
I wrote a demo project and posted it on GitHub that simulates handling an asynchronous network download. Take a look at DuncanMC/SwiftCompletionHandlers.
Specifically look at the method asyncFetchImage(), which does almost exactly what this thread is talking about: Uses an asynchronous method internally, and takes a completion block that it calls once the asynchronous load is done.
That is the general pattern you should use. Write a method that takes a completion block/closure. Internally, have that method call whatever asynchronous function it needs and then call your completion closure from inside the asynchronous method call's completion closure.
The function asyncFetchImage looks like this:
func asyncFetchImage(imageName imageName: String,
completion: (
image: UIImage?,
status: String) -> ())
{
print("Entering \(#function)")
//Simulate a network operation by waiting a few seconds before loading an image
let nSecDispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3.0 * Double(NSEC_PER_SEC)))
let queue = dispatch_get_main_queue()
dispatch_after(nSecDispatchTime, queue)
{
() -> Void in
let result = UIImage(named: imageName)
print("Loading image in background")
let status = result != nil ? "image loaded" : "Error loading image"
print("About to call completion handler")
completion(image: result, status: status)
}
print("Leaving \(#function)")
}