0

以下使用 AFNetworking 2.0 的代码可有效通过 Internet 获取数据:

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中测试这些代码)?

4

1 回答 1

1

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

为了解决这个问题,您只需告诉 AFNetworking 使用不同的调度队列。您可以通过将operationQueue属性设置为AFHTTPRequestOperationManager

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

// 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);
于 2013-11-05T20:56:28.700 回答