0

I want the first async function to be completed before the second async function gets called

I've tried this:

let group = dispatch_group_create();

//Execute First
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.LoadFirst("https://www.example.com/first.php", username: MyVariables.username as String)
});

//After Above is Finished then Execute
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.LoadSecond("https://www.example.com/second.php", username: MyVariables.username as String!)
}); 

But they are both running at the same time

2 Answers2

2

You have many options. Here are some:

1. Use your own serial dispatch queue:

let queue = dispatch_queue_create("com.mycompany.serial-queue",
    dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0))

dispatch_async(queue) {
    print("inside block 1")
}

dispatch_async(queue) {
    print("inside block 2")
}

2. Use NSOperationQueue with dependencies:

let queue = NSOperationQueue()

let op1 = NSBlockOperation {
    print("inside block 1")
}

let op2 = NSBlockOperation {
    print("inside block 2")
}

op2.addDependency(op1) // op2 may only execute after op1 is finished

queue.addOperation(op1)
queue.addOperation(op2)

3. Use a serial NSOperationQueue:

let queue = NSOperationQueue()
queue.maxConcurrentOperationCount = 1 // execute 1 operation at a time

queue.addOperationWithBlock {
    print("inside block 1")
}

queue.addOperationWithBlock {
    print("inside block 2")
}
jtbandes
  • 115,675
  • 35
  • 233
  • 266
1

Refactor your LoadFirst method (should be called loadFirst btw) to take a completion block and invoke it after the async task is complete. Then pass the call to loadSecond in the completion block to loadFirst.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • can you please provide an example? –  Oct 10 '15 at 19:36
  • I don't have time right now. I'm getting ready to go out for the evening. Look up how to define a method that takes a block as a parameter in the Apple Swift iBook. – Duncan C Oct 10 '15 at 19:37
  • The best I can do with the time I have is to point you to a project I put on Github that demonstrates how async completion handlers work: https://github.com/DuncanMC/SwiftCompletionHandlers.git. Take a look at the method `asyncFetchImage`. It takes a completion block that it invokes after it's async task is done. – Duncan C Oct 10 '15 at 19:50