JVS
JVS

Reputation: 2682

waiting for a function to finish with completion handler fails

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:

  1. Loading Data from Facebook makeRequest()
  2. Saving the Data to my Database 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

Answers (2)

CZ54
CZ54

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

Tarek hemdan
Tarek hemdan

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

Related Questions