SoFunction
Updated on 2025-04-07

Implement synchronization logic on asynchronous network requests in IOS development

Implement synchronization logic on asynchronous network requests in IOS development

premise:

You may encounter some problems, such as uploading multiple data, and you need to wait until multiple data is uploaded successfully to do some processing, and upload one by one. If one upload fails, there is no need to upload later, and an error will be reported directly.

Previously, ASI's network library had an interface for synchronous requests, so it is easy to handle. The network library of AFNetwork only had asynchronous network requests. How to implement it?

1. Loop asynchronous grouping

- (void)uploadFile:(NSArray *)imageArray atIndex:(NSInteger)index imagesCount:(NSInteger)count completeBlock:(uploadCompleteBlock)block {
 FNCircleImage *aTCImage = imageArray[index];
 NSString *filepath = ;
 [ upload:filepath progress:nil completion:^(NSString * _Nullable urlString, NSError * _Nullable error) {
  if (error == nil) {
    = urlString;

   NSInteger idx = index + 1;
   if (idx >= count) {
    block(nil);
   } else {
    [self uploadFile:imageArray atIndex:idx imagesCount:count completeBlock:block];
   }
  } else {
   block(error);
  }
 }];
}

2. Semaphore asynchronously to synchronously

__block NSError *e = nil;
[imageArray enumerateObjectsUsingBlock:^(NSString *filePath, NSUInteger idx, BOOL * _Nonnull stop) {
 __block dispatch_semaphore_t t = dispatch_semaphore_create(0);
 [self upload:filepath progress:nil completion:^(NSString * _Nullable urlString, NSError * _Nullable error) {
  if (error == nil) {
   
  } else {
   e = error;
   *stop = YES;
  }
  dispatch_semaphore_signal(t);
 }];
 dispatch_semaphore_wait(t, DISPATCH_TIME_FOREVER);
}];

Controllable queue

1). Inherit NSOperation to implement upload logic, complete notification or block callback

2). Create an Operation array using upload data and add it to NSOperationQueue to execute

3). Judging the result based on the result of completing the callback and the number of numbers. If there is a failure in the middle, you can close the unexecuted Operation.

Thank you for reading, I hope it can help you. Thank you for your support for this site!