Acoop
Acoop

Reputation: 2666

Run code only after asynchronous function finishes executing

I am relatively new to Swift and Xcode in general and am finding a lot of difficulty trying to figure this out.

I am developing an app that utilizes the Parse.com backend server. In order not to block the main thread, whenever the app downloads anything from the server, it is done on a different thread, asynchronously. However the rest of the code continues to execute on the main thread, and it crashes when the data it is supposed to have from the server has not downloaded yet. I would like to know how to call functions to run after the asynchronous function finishes, and this has to be done for functions in separate files.

I read that closures might help with this, but I found there syntax very difficult and an explanation would be greatly appreciated. But any way would be very helpful.

Thanks

Upvotes: 9

Views: 6973

Answers (2)

matt
matt

Reputation: 535790

Well, you simply call the function at the end of the asynchronous callback. That is when the asynchronous callback has ended - it is when everything else in the asynchronous callback has finished! So, for example:

func myMethod() {
    // ... code ...
    somebody.doSomethingWith(someObject, asynchronousCallback: {
        (thing, otherThing) in
        // ... do whatever
        // --> CALL THE FUNCTION!
    })
    // ... code ...
}

If the problem is that you do not know what function to call, you can configure your surrounding function / object so that someone can hand you a function which is then what you call in the spot where I said "call the function" in the above.

For example:

func myMethod(f:() -> ()) { // we receive the function as parameter
    // ... code ...
    somebody.doSomethingWith(someObject, asynchronousCallback: {
        (thing, otherThing) in
        // ... do whatever
        // --> CALL THE FUNCTION, by saying:
        f()
    })
    // ... code ...
}

Upvotes: 14

Duncan C
Duncan C

Reputation: 131481

Expanding on Matt's answer, you can make myMethod a method that takes a closure as a parameter:

​func​ ​myMethod​(​completionBlock​: (result: String) -> ()) 
{
    // ... code ...
    somebody.doSomethingWith(someObject, asynchronousCallback: {
        (thing, otherThing) in
        // ... do whatever
        completionBlock(thing)
    })
    // ... code ...
}

Upvotes: 3

Related Questions