Reputation: 2682
I am trying to wait for an asynchronous function to finish before processing it's data (e.g. saving it to my database).
I have a function loadFacebookDetails()
containing two tasks:
makeRequest()
saveAndProceed()
I need makeRequest()
-> (asynchronous) to finish before handling the saving.
This is what I got so far:
I declared a typealias FinishedDownload = () -> ()
I created:
func makeRequest(completed: FinishedDownload){
.... // bunch of code
completed() // call that I completed my task at end of function
}
now I don't now how to call makeRequest in my loadFacebookDetails.
I also created this:
makeRequest { () -> () in
saveAndProceed()
}
and my saveAndProceed(). Does anyone now how to make this syntactical correct?
Upvotes: 0
Views: 1021
Reputation: 5586
You should have something like :
func makeRequest(completion : ( ( Bool ) -> Void)){
//your stuff goes hre
completion(true)
//or
completion(false)
}
func saveAndProceed() {
//your stuff
}
func loadFacebookDetails() {
makeRequest { (hasSucceed) in
if hasSucceed {
saveAndProceed()
}else{
//handle Error
}
}
}
Upvotes: 1
Reputation: 874
func makeRequest(url: String ,callback :@escaping (YourObject) -> Void , errorCallBack : @escaping (String) -> Void ){
// if finish or success
callback(objecttoSend);
// or if failed
errorCallBack(message)
}
and call it like this
makeRequest(url: "http://", callback: {(Object)in
// on ur first action
}, errorCallBack: {(error)in
// on ur second action
})
Upvotes: 0