利用 GCD 信号量、NSOperation管理请求

需求:若干个request依次执行,若其中一个失败,则取消剩余未执行的request

1.自定义operation

// .h实现如下
@protocol CustomOperationDelegate 

- (void)cancelAllRequest:(NSInteger)index params:(NSDictionary *)dict isSuccess:(BOOL)isSuccess;

@end
@interface CustomOperation : NSOperation

@property (nonatomic, copy) NSString *params;
@property (nonatomic, strong) dispatch_semaphore_t sema;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, weak) id delegate;

@end 
#import 

@implementation CustomOperation

- (void)main {
    if (!self.isCancelled) {
        NSString * url = [NSString stringWithFormat:@"%@%@",@"http://220.174.234.36:8090/GasAPITest/",@"house/customerNoHouse"];
        NSMutableDictionary * paraDic = [NSMutableDictionary dictionary];
        [paraDic setObject:self.params forKey:@"customerNo"];
        
        __block BOOL isSuccessed = YES;
        __block NSDictionary *dict = [NSDictionary dictionary];
        
        [[AFHTTPSessionManager manager] POST:url parameters:paraDic
                                    progress:^(NSProgress * _Nonnull uploadProgress) {
                                        
                                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                        if ([responseObject[@"result"] isEqualToString:@"success"]) {
                                            isSuccessed = YES;
                                            dict = responseObject;
                                        } else {
                                            isSuccessed = NO;
                                        }
                                        dispatch_semaphore_signal(self.sema);
                                        
                                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                        isSuccessed = NO;
                                        dispatch_semaphore_signal(self.sema);
                                        
                                    }];
        
        dispatch_semaphore_wait(self.sema, DISPATCH_TIME_FOREVER);
        
        [self.delegate cancelAllRequest:self.index params:dict isSuccess:isSuccessed];

    }
}
@end 
  1. 应用如下
#import "ViewController.h"
#import "CustomOperation.h"

@interface ViewController () 

@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, strong) NSMutableArray *array;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.array = [NSMutableArray array];
    
    self.queue = [[NSOperationQueue alloc] init];
    self.queue.maxConcurrentOperationCount = 1;
    dispatch_semaphore_t semaphore =dispatch_semaphore_create(0);
    
    CustomOperation *operationToAdd;
    NSArray *gasNumberArr =@[@"00047449",@"00047449",@"3",@"00047449",@"00047449"];
    for (NSInteger i=0; i

3.结果如下:


你可能感兴趣的:(利用 GCD 信号量、NSOperation管理请求)