
AFNetworking 同步请求?怎么会有这样的设计~有时候确实存在这样的情况和需求,哎硬着头皮解决吧!
其实ajax实现同步和异步很简单,只要设置async的属性值就行,默认的设置值为true,这种情况为异步方式,就是说当ajax发送请求后,在等待server端返回的这个过程中,前台会继续 执行ajax块后面的脚本,直到server端返回正确的结果才会去执行success,也就是说这时候执行的是两个线程,ajax块发出请求后一个线程 和ajax块后面的脚本(另一个线程),两个线程互不影响。(2)通信成功但是不能同步登陆多线程死锁的伪代码,用火狐的firebug跟踪请求发现根本没有同步登 陆的请求,而且还报错:bad request,invalid hostname,百思不得其解,果断百度一下发 现是discuz后台->站长->ucenter设置中ip地址是127.0.0.1,直接 去掉,但是还不能同步登陆,跟踪discuz同步登陆的代码发现$_g['setting']['allowsynlogin']是 0但是 ucenter应用管理中明明已经开启同步登陆,于是想到可能是缓存的原因,去discuz后台更新缓存,结果同步登陆终于ok。(2)通信成功但是不能同步登陆,用火狐的firebug跟踪请求发现根本没有同步登 陆的请求,而且还报错:bad request,invalid hostname,百思不得其解,果断百度一下发现是discuz后台->站长->ucenter设置中ip地址是127.0.0.1,直接 去掉,但是还不能同步登陆,跟踪discuz同步登陆的代码发现$_g['setting']['allowsynlogin']是0但是 ucenter应用管理中明明已经开启同步登陆,于是想到可能是缓存的原因,去discuz后台更新缓存,结果同步登陆终于ok。
于是开始着手调研,参考网上提供的思路,以及大神解答多线程死锁的伪代码,查看大神么的回复发现,确实AF使用信号量会造成死锁,造成死锁的原因是AF默认的回调都是在mainQueue上执行的。而主线程因为dispatch_semaphore_wait的关系锁死了,AF的回调需要等待主线程解锁后才会继续。。而解锁的钥匙却在回调里。知道了原因可以还是不知道怎么解决,知道了思路就多了调查方向,继续调查,终于在stackoverflow上找到了解决办法。将AF的回调队列放到全局队列(dispatch_get_global_queue)中,问题迎刃而解,将自己的成功记录下来,供以后参考。具体实现直接上代码:
- (id)sendForUrl:(NSURL *)url {
tools > nuget package manager > package manager console。zhai hongxin, general manager, corporate social responsibility。the paid manager acting for the company was inmore direct relation with the men and theirdemands, but even he had seldom that familiarpersonal knowledge of the workmen which theemployer had often had under the more patriarchalsystem of the old family business now passing away.。

dispatch_group_async(group, dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{。dispatch_group_async(group, dispatch_get_global_queue(dispatch_queue_priority_default, 0), ^{。#define xzglobalqueue dispatch_get_global_queue(dispatch_queue_priority_default, 0)。
dispatch_semaphore_t _semaphore。dispatch_semaphore_t signal = dispatch_semaphore_create(1)。 dispatch_semaphore_t sema = dispatch_semaphore_create(0)。
__block id response;
[networkmanager requestwithmethod:post url:url parameters:paradic success:^(id responseobject) {。afhttprequestoperation*operation=[[afhttprequestoperationalloc]initwithrequest:request]。 [manager post:loginurl parameters:params progress:nil success:^(nsurlsessiondatatask * _nonnull task, id _nullable responseobject) {。
response = responseObject;

NSLog(@"JSON: %@", responseObject);
dispatch_semaphore_signal(semaphore);
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
dispatch_semaphore_signal(semaphore);

}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return response;
}
经过测试,非常完美~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

也可使用别人对AF扩展的同步请求AFNetworking-Synchronous 本人没有测试,不能保证
语言&技术能力有限,如有不恰当的地方欢迎指正批评。
参考链接:
1:Wait for AFNetworking completion block before continuing (i.e. Synchronous)
2:周末有人没 ,请教AFN3.0同步请求的问题
3:Synchronous request
4:AFNetworking的线程和信号量问题
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-117024-1.html
没人觉得
都是这样的状态
从我做起