举例:比如A、B两个请求,B必须等待A完成才执行。像这种情况的话很多人都在A请求完成的回调里面写,这样是可以的,但是要实现同步的话还有两种方法,一个是 GCD 里面的 barrier 函数,另外一个是 GCD 里面信号量的方式,我觉得信号量的方式是更灵活的处理,代码入下:
dispatch_semaphore_t semap = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[AFNetworking requestWithURLString:BASEURLWITH(@"login")
parameters:@{@"email":@"fucc@gmail.com",
@"password":@"xxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"a完成");
dispatch_semaphore_signal(semap);
} failure:^(NSError *error) {
NSLog(@"a完成,但是失败了");
dispatch_semaphore_signal(semap);
}];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//等待信号30s,如果超过30s的话,则进入 if 方法,否则就进入 else 方法
//超时返回1
if (dispatch_semaphore_wait(semap, dispatch_time(DISPATCH_TIME_NOW,
30 * NSEC_PER_SEC)))
{
//处理超时
//也可以把超时时间设置成forever,会一直等待直到收到信号
}
//不超时返回0
else {
[AFNetworking requestWithURLString:BASEURLWITH(@"login")
parameters:@{@"email":@"fucc@gmail.com",
@"password":@"xxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"b完成");
} failure:^(NSError *error) {
NSLog(@"b完成,但是失败了");
}];
}
});
举例:A、B、C三个请求,ABC都完成,并且成功再执行下一个动作。
错误示范:int i = 0,A 完成 i++,B 完成 i++, C完成 i++,然后在A、B、C三个请求的成功回调里,都进行判断 i==3,这样会出错的原因是,3个请求同时完成的话,i = 1。
正确示范代码入下:
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_enter(dispatchGroup);
NSLog(@"1");
[AFNetworking requestWithURLString:BASEURLWITH(@"login1")
parameters:@{@"email":@"fucc1@gmail.com",
@"password":@"xxxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"1完成");
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
NSLog(@"%@",error);
}];
dispatch_group_enter(dispatchGroup);
NSLog(@"2");
[AFNetworking requestWithURLString:BASEURLWITH(@"login2")
parameters:@{@"email":@"fucc2@gmail.com",
@"password":@"xxxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"2完成");
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
NSLog(@"%@",error);
}];
dispatch_group_enter(dispatchGroup);
NSLog(@"3");
[AFNetworking requestWithURLString:BASEURLWITH(@"login3")
parameters:@{@"email":@"fucc3@gmail.com",
@"password":@"xxxxxxxx"}
type:HttpRequestTypePost
success:^(id responseObject) {
NSLog(@"3完成");
dispatch_group_leave(dispatchGroup);
} failure:^(NSError *error) {
NSLog(@"%@",error);
}];
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"3个请求完成");
});
网友评论