我正在使用 AFNetworking 套件开发 iOS 应用。
当应用程序启动时,它会从服务器请求访问 token 。
代码很简单:
__block int status = 0;
[manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
...fetch access token from response json string
status = 1; //break the loop
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
...networking error
}
而且,为了确保对服务器的其他请求拥有访问 token ,我设置了一个循环来阻塞线程,直到服务器响应为止。
while (status == 0)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate date]];
}
这在我导入第三方通知推送库之前一直有效。和异步方法:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
继续在控制台中打印 deviceToken
请求,访问 token 请求从不响应任何内容,即使服务器实际提供了响应。
我被困了一天,有人可以帮助我吗?
更新我已经尝试评论设备 token 的东西,AFNetworking 请求仍然不起作用,没有成功没有失败也没有超时:
UPDATE2 澄清我的问题。 AFHTTPRequestOperationManager
向服务器发送 GET 请求,并得到服务器响应。但是 AFHTTPRequestOperationManager
没有接收到它,并且没有成功也没有失败回调。
最佳答案
几个想法:
如果您要使用此模式:
您真的应该在错误 block 中也将
status
设置为1
;和Apple 在其示例中使用
distantFuture
,而不是date
:[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
您可能有其他东西阻塞了主线程。尝试将
NSLog
放入while
循环中,看看您是否看到该循环正在运行。如果不是,则确定阻塞主线程的位置。不用说,这种整体模式效率低下。我建议采用异步模式,例如在您自己的代码中采用完成处理程序:
- (void)performSomeURL:(NSString *)url completionHandler:(void (^)(NSDictionary *response, NSError *error))completionHandler{ NSDictionary *parameters = ...; [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { completionHandler(responseObject, nil); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { completionHandler(nil, error); }]; }
可以这样称呼:
[self performSomeURL:url completionHandler:^(NSDictionary *response, NSError *error) { // use response and error here }]; // but not here
如果你在你的所有代码中总是采用这样的异步模式,从不做任何阻塞主线程的事情,那么你的代码不仅会更有效率,而且你永远不必担心主线程上的死锁.
关于ios - AFHTTPRequestOperationManager 没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33495547/