AFNetworking 同步请求 有谁教教我
展开全部
原来使用ASI,同步异步都有,但是,AFNETWORKING没有同步调用,全是异步,封装了个试试.
就是用个NSCondition 搞个等待就OK了.
-(NSDictionary*)reqUtil:(NSString*)reqURLStr
{
NSCondition* itlock = [[NSCondition alloc] init];//搞个事件来同步下
NSLog(@"reqstr:%@",reqURLStr);
__block NSDictionary* itret = nil;
//AFNETWORKING 异步请求
[self getPath:reqURLStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//执行成功之后的BLOCK代码
//得到了数据
JSONDecoder *jd=[[JSONDecoder alloc] init];
NSDictionary* tt = [jd objectWithData:responseObject];
itret = [[NSDictionary alloc] initWithDictionary:tt];
[itlock lock];
[itlock signal];//设置事件,下面那个等待就可以收到事件返回了
[itlock unlock];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"neterr:%@",[error localizedDescription]);
[_delegate didFailedUpdateWithError:error];
[itlock lock];
[itlock signal];//失败也要设置事件,不然下面一直死等了
[itlock unlock];
}];
[itlock lock];//启动AFNETWORKING之后就等待事件
[itlock wait];
[itlock unlock];
return itret;
}
注意:该函数千万不能在主线程调用,因为上述的成功,失败 BLOCK代码afnetworking会切换到主线程来执行,但是,主线程已经被 [itlock wait]; 等死了,这样afnetworking 在切换到主线程执行BLOCK的时候也会被等死,就死锁了.
就是用个NSCondition 搞个等待就OK了.
-(NSDictionary*)reqUtil:(NSString*)reqURLStr
{
NSCondition* itlock = [[NSCondition alloc] init];//搞个事件来同步下
NSLog(@"reqstr:%@",reqURLStr);
__block NSDictionary* itret = nil;
//AFNETWORKING 异步请求
[self getPath:reqURLStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//执行成功之后的BLOCK代码
//得到了数据
JSONDecoder *jd=[[JSONDecoder alloc] init];
NSDictionary* tt = [jd objectWithData:responseObject];
itret = [[NSDictionary alloc] initWithDictionary:tt];
[itlock lock];
[itlock signal];//设置事件,下面那个等待就可以收到事件返回了
[itlock unlock];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"neterr:%@",[error localizedDescription]);
[_delegate didFailedUpdateWithError:error];
[itlock lock];
[itlock signal];//失败也要设置事件,不然下面一直死等了
[itlock unlock];
}];
[itlock lock];//启动AFNETWORKING之后就等待事件
[itlock wait];
[itlock unlock];
return itret;
}
注意:该函数千万不能在主线程调用,因为上述的成功,失败 BLOCK代码afnetworking会切换到主线程来执行,但是,主线程已经被 [itlock wait]; 等死了,这样afnetworking 在切换到主线程执行BLOCK的时候也会被等死,就死锁了.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询