Skip to content

Instantly share code, notes, and snippets.

@yuxiangq
Last active May 19, 2017 14:20
Show Gist options
  • Save yuxiangq/5a6fda885689df3ef4e6 to your computer and use it in GitHub Desktop.
Save yuxiangq/5a6fda885689df3ef4e6 to your computer and use it in GitHub Desktop.
NSOperationQueue 实现串行请求
//用了表示是否有异步请求正在执行
@property (assign, atomic) BOOL excuting;
@property (strong, nonatomic) NSArray *datasArray;
@property (strong, nonatomic) NSOperationQueue *operationQueue;
- (void)ViewDidLoad {
[super viewDidLoad];
self.excuting = NO;
self.operationQueue = [[NSOperationQueue alloc] init];
[self.operationQueue setMaxConcurrentOperationCount:1];
NSInvocationOperation *previousOperation = nil;
for(id data in datasArray) {
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(uploadDataToServer:)
object:data];
if(previousOperation) {
[operation addDependency:previousOperation]
}
[self.operationQueue addOperation:operation];
previousOperation = operation;
}
}
- (void)uploadDataToServer:(id)data {
NSURL *url = [NSURL URLWithString:@"https://api/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:60];
[request setHTTPBody:data];
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]
dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
if (error) {
//该任务执行有错误,取消后续任务
[self.operationQueue cancelAllOperations];
}
else {
self.excuting = false;
}
}];
//如果有其他任务正在执行,则阻塞当前任务
while(self.excuting) {
}
//开始当前任务
[dataTask resume];
self.excuting = YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment