Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running one function after another completes

Tags:

ios

swift

I am trying to run loadViews() after the pullData() completes and I am wondering what the best way of doing this is? I would like to set a 10 sec timeout on it as well so I can display a network error if possible. From what I have read, GCD looks like it is the way to accomplish this but I am confused on the implementation of it. Thanks for any help you can give!

//1
pullData()
//2
loadViews()
like image 946
Opei Avatar asked Feb 12 '16 08:02

Opei


2 Answers

What you need is a completion handler with a completion block.

Its really simple to create one:

func firstTask(completion: (success: Bool) -> Void) {
    // Do something

    // Call completion, when finished, success or faliure
    completion(success: true)
}

And use your completion block like this:

firstTask { (success) -> Void in
    if success {
       // do second task if success
       secondTask()
    }
}
like image 130
Dejan Skledar Avatar answered Oct 19 '22 06:10

Dejan Skledar


You can achieve like this :-

func demo(completion: (success: Bool) -> Void) {
     // code goes here
   completion(success: true)
}
like image 36
pradeepchauhan_pc Avatar answered Oct 19 '22 06:10

pradeepchauhan_pc