Anil Kumar R
Anil Kumar R

Reputation: 1

In for loop, How to wait for a process to complete before jumping to next iteration? (iOS)

sample code :

for (int i = 0; i < 5; i++)  
{  
    NSLog(@"%d Iteration started",i); 
   [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:      ^(NSData * _Nullable data,        NSURLResponse * _Nullable response,        NSError * _Nullable error) {     
    NSLog(@"%d iteration completed ",i);  
    }] resume];
}

//Log inside the block should execute before moving to next iteration!

Upvotes: 0

Views: 260

Answers (1)

bbum
bbum

Reputation: 162712

A completion handler is exactly that; a handler that is called on completion of a task.

If you want the next task to kick off when the current task is complete, then trigger it from the completion handler.

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:      ^(NSData * _Nullable data,        NSURLResponse * _Nullable response,        NSError * _Nullable error) {     
    NSLog(@"%d iteration completed ",i);
    // kick off next request here.
}] resume];

Upvotes: 1

Related Questions