slider
slider

Reputation: 2816

Using GCD to call function after another function in Swift

I have a function A that contains two other functions B & C. Inside function A I need to call function C once function B has completed. I'm thinking I need to use Grand Central Dispatch's dispatch_group_notify for it, but am not too sure how to use it. I'm calling asynchronous methods in both functions B & C. Here are my functions:

func A() {

    func B() {

    // Three asynchronous functions

    }

    func C() {

    // More asynchronous functions that handle results from func B()

    }

    funcB()
    funcC()
}

EDIT: In func B(), I have three async functions that take awhile to finish. When I use the following method, func C() is still being called before the methods within func B() are completely finished. How do I make sure they're completely finished before the second dispatch group is called?

func A() {

var group = dispatch_group_create()

        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { () -> Void in

            // async function 1
            // async function 2
            // async function 3
        }

        dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in

           // async function

        })

}

Upvotes: 2

Views: 1541

Answers (1)

zrzka
zrzka

Reputation: 21259

Here's an example how to wait till your tasks are finished:

func asyncTaskSimulation(delay: NSTimeInterval, completion: (NSTimeInterval) -> ()) {
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
    Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
      completion(delay)
  }
}

func A() {

  func B(completion: () -> ()) {

    print("Function B start")

    let group = dispatch_group_create()

    dispatch_group_enter(group)
    asyncTaskSimulation(1.0) { (delay) in
      print("First task after \(delay)s")
      dispatch_group_leave(group)
    }

    dispatch_group_enter(group)
    asyncTaskSimulation(2.0) { (delay) in
      print("Second task after \(delay)s")
      dispatch_group_leave(group)
    }

    dispatch_group_enter(group)
    asyncTaskSimulation(0.5) { (delay) in
      print("Third task after \(delay)s")
      dispatch_group_leave(group)
    }

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
    completion()

    print("Function B end")
  }

  func C() {
    print("Function C start")
    print("Whatever")
    print("Function C end")
  }

  B() {
    C()
  }

}

A()

Here's the output:

Function B start
Second task after 0.5s
First task after 1.0s
Second task after 2.0s
Function C start
Whatever
Function C end
Function B end

Upvotes: 1

Related Questions