如何同步使用AFNetworking 2.0库?

时间:2013-09-30 03:28:07

标签: ios asynchronous afnetworking-2

以下使用AFNetworking 2.0的代码可以通过互联网获取数据:

NSString *URLPath = @"http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=json";
NSDictionary *parameters = nil;

[[AFHTTPRequestOperationManager manager] GET:URLPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"success: %@", responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"failure: %@", error);
}];

但我想在单元测试中同步测试这些请求。但是当使用这样的GCD信号量时它会被阻止:

// This code would be blocked.
dispatch_semaphore_t sema = dispatch_semaphore_create(0);

NSString *URLPath = @"http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=json";
NSDictionary *parameters = nil;

[[AFHTTPRequestOperationManager manager] GET:URLPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"success: %@", responseObject);
    dispatch_semaphore_signal(sema);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"failure: %@", error);
    dispatch_semaphore_signal(sema);

}];

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release_ARC_compatible(sema);

如何同步使用AFNetworking 2.0库获取数据(在Kiwi中测试这些代码)?

1 个答案:

答案 0 :(得分:1)

您的信号量将被阻止,因为默认情况下AFNetworking在主循环上运行。因此,如果您正在等待信号量的主循环,AFNetworking的代码永远不会运行。

为了解决这个问题,您只需要告诉AFNetworking使用不同的调度队列。您可以通过在AFHTTPRequestOperationManager

上设置operationQueue属性来实现

您可以创建自己的调度队列,也可以使用其中一个预定义队列,如下所示:

// Make sure that the callbacks are not called from the main queue, otherwise we would deadlock
manager.operationQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);