在开发中曾经遇到一个这样的问题:
在过渡到一个新的Controller之前,有一些数据是必须先传递过去的,但是这些数据必须从不同的接口中获取。
也就是从接口A中获取data1,从接口B中获取data2,将data1和data2赋值给Controller的属性,然后再push过去。push这个动作依赖于data1和data2。
最简单的方法可以在接口A的请求的成功和失败的回调中去执行一个接口B的请求,然后在B的成功或者失败的回调中去做push的动作。但是这样的做法代码会很丑陋,而且B的请求变成依赖于A的请求的回调完成。
使用NSOperation解决
如果了解NSOperation的一些API(可见上一篇NSOperation),很容易想到通过给NSOperation设置依赖来解决:
- (void)orginalOp{
NSString *url1 = @"http://www.baidu.com";
NSString *url2 = @"//www.greatytc.com";
NSOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
[self getHtmlOfUrl:url1 success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable response) {
NSLog(@"get data of %@ success",url1);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"get html of %@ fail",url1);
}];
}];
NSOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
[self getHtmlOfUrl:url2 success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable response) {
NSLog(@"get data of %@ success",url2);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"get html of %@ fail",url2);
}];
}];
NSOperation *pushOp = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"push to new controller after all data is ready!");
}];
[pushOp addDependency:op1];
[pushOp addDependency:op2];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperation:pushOp];
}
- (void)getHtmlOfUrl:(NSString *)url
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure{
url = [url stringByRemovingPercentEncoding];
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
sessionManager.responseSerializer.acceptableContentTypes = [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
[sessionManager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(task,responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(task,error);
}];
}
查看运行结果:
2017-04-21 09:24:49.367 ConcurrentProgram[3733:210543] push to new controller after all data is ready!
2017-04-21 09:24:49.791 ConcurrentProgram[3733:195552] get data of //www.greatytc.com success
2017-04-21 09:24:49.802 ConcurrentProgram[3733:195552] get data of http://www.baidu.com success
显然并没有达到我们预期的效果。稍作分析即可理解:pushOp依赖于op1和op2的完成,那么op1和op2什么时候完成呢?在本例中,由于请求是异步的,并不是获取到请求结果之后才完成,而是执行完请求动作之后该operation就已经算是完成了。所以就会有上述的结果。
那么要怎么样才能把operation的完成设置在请求成功或者失败之后呢?NSOperation中有一个isFinished的方法,如果该方法返回YES那么就代表operation已经完成了。所以,我们要新建一个类继承NSOperation来实现这个需求。代码如下:
#import "AFRequestOperation.h"
@interface AFRequestOperation (){
BOOL finished;
BOOL executing;
}
@end
@implementation AFRequestOperation
- (instancetype)init{
self = [super init];
if (self) {
finished = NO;
executing = NO;
}
return self;
}
- (void)start{
// Always check for cancellation before launching the task.
if ([self isCancelled])
{
// Must move the operation to the finished state if it is canceled.
[self willChangeValueForKey:@"isFinished"];
finished = YES;
[self didChangeValueForKey:@"isFinished"];
return;
}
// If the operation is not canceled, begin executing the task.
[self willChangeValueForKey:@"isExecuting"];
executing = YES;
[self didChangeValueForKey:@"isExecuting"];
[self performTask];
}
- (void)performTask{
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
sessionManager.responseSerializer.acceptableContentTypes = [sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
[sessionManager GET:_url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (self.successHandler) {
self.successHandler(responseObject);
}
[self willChangeValueForKey:@"isExecuting"];
executing = NO;
[self didChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
finished = YES;
[self didChangeValueForKey:@"isFinished"];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (self.errorHandler) {
self.errorHandler(error);
}
[self willChangeValueForKey:@"isExecuting"];
executing = NO;
[self didChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
finished = YES;
[self didChangeValueForKey:@"isFinished"];
}];
}
- (BOOL)isFinished {
return finished;
}
- (BOOL)isExecuting {
return executing;
}
@end
在调用的时候:
- (void)customOp{
NSString *url1 = @"http://www.baidu.com";
NSString *url2 = @"//www.greatytc.com";
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
AFRequestOperation *op1 = [[AFRequestOperation alloc] init];
op1.url = url1;
op1.successHandler = ^(id response) {
NSLog(@"get data of %@ success",url1);
};
op1.errorHandler = ^(NSError *error) {
NSLog(@"get data of %@ fail",url1);
};
[queue addOperation:op1];
AFRequestOperation *op2 = [[AFRequestOperation alloc] init];
op2.url = url2;
op2.successHandler = ^(id response) {
NSLog(@"get data of %@ success",url2);
};
op2.errorHandler = ^(NSError *error) {
NSLog(@"get data of %@ fail",url2);
};
[queue addOperation:op2];
NSOperation *pushOp = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"push to new controller after all data is ready!");
}];
[pushOp addDependency:op1];
[pushOp addDependency:op2];
[queue addOperation:pushOp];
}
运行结果如下:
2017-04-21 09:37:54.833 ConcurrentProgram[4225:249946] get data of http://www.baidu.com success
2017-04-21 09:37:54.988 ConcurrentProgram[4225:249946] get data of //www.greatytc.com success
2017-04-21 09:37:54.988 ConcurrentProgram[4225:262299] push to new controller after all data is ready!
为了可以兼容不同的请求这里把一个请求的url以及成功和失败的回调等传入自定义的operation中。最关键的一点就在于完成请求的成功或者失败的回调之后将isFinish设置为YES,此时operation才算是完成。
使用GCD解决
虽然这样可以解决这个问题,但是看起来比较复杂,要写一个类继承自NSOperation。之前也了解过GCD,那么能否考虑是使用GCD的方式来解决呢?
GCD中有一个dispatch_group_t的API,使用dispatch_group_t可以监控一组block,dispatch_group_t会追踪组内的block的执行状态,当group中所有的block完成以后,可以使用dispatch_group_notify来执行一个额外的block。增加dispatch_group_t中block的数量有两种方式,一种是使用dispatch_group_async或者dispatch_group_sync后面添加block,另外一种是使用dispatch_group_enter和dispatch_group_leave组合来代表一个block的开始和结束。在这里我们需要使用dispatch_group_enter和dispatch_group_leave组合。
代码如下:
- (void)gcdGroup{
NSString *url1 = @"http://www.baidu.com";
NSString *url2 = @"//www.greatytc.com";
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[self getHtmlOfUrl:url1 success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable response) {
NSLog(@"get data of %@ success",url1);
dispatch_group_leave(group);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"get html of %@ fail",url1);
dispatch_group_leave(group);
}];
dispatch_group_enter(group);
[self getHtmlOfUrl:url2 success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable response) {
NSLog(@"get data of %@ success",url2);
dispatch_group_leave(group);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"get html of %@ fail",url2);
dispatch_group_leave(group);
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"push to new controller after all data is ready!");
});
}
实际上dispatch_group_t代表了一个信号量,该信号量有一个初始值。当调用dispatch_group_enter时该信号量的值-1,而掉用dispatch_group_leave的时候信号量的值加1.让信号量的值等于初始值时,就会执行dispatch_group_notify中的block。有兴趣的可以自己尝试一下使用dispatch_group_async看能不能解决异步任务依赖的需求。我个人的实验结果是和第一个例子的结果是一样的。