ios - AFHTTPRequestOperationManager 没有响应

标签 ios multithreading apple-push-notifications afnetworking-2

我正在使用 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 没有接收到它,并且没有成功也没有失败回调。

最佳答案

几个想法:

  1. 如果您要使用此模式:

    • 您真的应该在错误 block 中也将 status 设置为 1;和

    • Apple 在其示例中使用 distantFuture,而不是 date:

      [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
      
  2. 您可能有其他东西阻塞了主线程。尝试将 NSLog 放入 while 循环中,看看您是否看到该循环正在运行。如果不是,则确定阻塞主线程的位置。

  3. 不用说,这种整体模式效率低下。我建议采用异步模式,例如在您自己的代码中采用完成处理程序:

    - (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/

相关文章:

c# - 如何在不排队的情况下从 C# 发送 APNS 推送通知 (iOS)

ios - 如何使用 swift 在 IOS 中的两个扩展之间共享变量值而不使用 Coredata

ios - iOS 中的 8 位图像

ios - SwiftUI 无法为图像过渡设置动画

windows - CreateThread() 在 64 位 Windows 上失败,在 32 位 Windows 上工作。为什么?

ios - 当应用程序在后台使用 Sinch iOS SDK 时无法处理来电推送通知

ios - 为什么搜索栏没有从解析中提取用户?

java - 线程之间的信号

java - 调用某个线程的 start() 方法后,主线程是否立即获得控制权?

ios - [iOS]用户手动杀掉应用后接收推送通知的处理