Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

ios - 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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...