Implementation of Synchronization Logic on Asynchronous Network Request in IOS Development

  • 2021-12-05 07:35:36
  • OfStack

Implementation of Synchronization Logic on Asynchronous Network Request in IOS Development

Premises:

May encounter some problems, such as uploading multiple data, need to wait for multiple data to be uploaded successfully, and upload them one by one, which fails to upload, do not need to upload later, and report errors directly.

Before ASI network library is a synchronous request interface, so it is very easy to handle, AFNetwork network library only asynchronous network request, how to achieve it?

1. Loop asynchronous grouping


- (void)uploadFile:(NSArray *)imageArray atIndex:(NSInteger)index imagesCount:(NSInteger)count completeBlock:(uploadCompleteBlock)block {
 FNCircleImage *aTCImage = imageArray[index];
 NSString *filepath = aTCImage.localFilePath;
 [self.resourceManager upload:filepath progress:nil completion:^(NSString * _Nullable urlString, NSError * _Nullable error) {
  if (error == nil) {
   aTCImage.remoteUrl = 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 asynchronous to synchronous


__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);
}];

3. NSOperationQueue controllable queue

1). Inherit NSOperation to realize upload logic, and complete sending notification or block callback

2) Create an Operation array with uploaded data and add it to NSOperationQueue for execution

3). According to the result and number of callbacks, if there is a failure in the middle, the unexecuted Operation can be closed

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: