Wait for the first async function to complete, and then execute the second async function

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

I 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 both work simultaneously

0
source share
2 answers

You have many options. Here are some of them:

1. Use your own sequential send 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 the 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") } 
+1
source

Restore your LoadFirst method (should be called loadFirst btw) to take the completion block and call it after the async task completes. Then pass the call to loadSecond in the completion block to load First.

+1
source

Source: https://habr.com/ru/post/1241385/


All Articles