2013-09-30 36 views
0

使用AFNetworking 2.0下面的代碼是有效的,通過互聯網來獲取數據:如何同步使用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); 
}]; 

但我想在單元測試同步測試這些請求。

// 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這些代碼):但是,如果使用這樣當GCD信號受阻?

+0

爲什麼你不能使用信號燈? –

+0

首先,思考你正在測試的代碼 - 你真的想爲AFNetworking編寫單元測試嗎?他們已經有自己的。那麼,你試圖用這個來測試呢? –

+0

我想測試其他提供的Web API。 –

回答

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); 
+0

這是不行的,'''dispatch_get_global_queue'''不會返回一個NSOperationQueue – dwery

+0

@dwery我的壞。我沒有代碼了,所以我不能看看我做了什麼,但是獲得NSOperationQueue應該不會太難。 – gregschlom