對於我的應用程序,我必須連接到兩個返回JSON的webservices。IOS/AFNetworking:排隊兩個JSON操作,然後比較返回的NSArrays
我第一次使用GCD推出自己的網絡代碼,但看到AFNetworking如何處理事情,我決定實現它。大部分事情都沒有問題,但是在某些時候我正在檢索兩個充滿對象的數組。這兩個數組然後使用不同的方法進行比較。不知怎的,實際的排隊是延遲或不工作,這取決於我使用的代碼。
使用:
NSArray *operations = [NSArray arrayWithObjects:operation, operation1, nil];
AFHTTPClient *client = [[AFHTTPClient alloc]init];
[client enqueueBatchOfHTTPRequestOperations:operations progressBlock:nil completionBlock:^(NSArray *operations) {
[self compareArrays:self];
}
它只是掛起。
當使用:
[operation start];
[operation1 start];
[operation waitUntilFinished];
[operation1 waitUntilFinished];
[self compareArrays:self];
在端,它得到的陣列,但只有UI已經形成之後進行比較。
編輯: 我檢查了戴夫的答案,它看起來非常精簡。 我的應用會受益於使用AFHTTPClient
,還是這種方法(使用AFJSONRequestOperation
)提供相同的功能?我記得AFHTTPClient
現在自己處理可達性(儘管你需要設置它)。我擺弄了一下週圍,並得到了這個工作:
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
WebServiceStore *wss = [WebServiceStore sharedWebServiceStore];
self.userData = wss.userData;
serviceURL = [NSString stringWithFormat: @"WEBSERVICE URL"];
NSString* zoekFruit = [NSString stringWithFormat:
@"%@?customer=%@&gebruiker=%@&password=%@&breedte=%@&hoogte=%@&diameter=%@",
serviceURL,
self.userData.Klant,
self.userData.Gebruiker,
self.userData.Wachtwoord,
breedte,
hoogte,
diameter];
NSURL *url = [NSURL URLWithString:[zoekFruit stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
id results = [JSON valueForKey:@"data"];
[results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//Initiate the BWBand
BWBand *band = [[BWBand alloc]init];
//Set the BWBand's properties with valueforKey (or so).
[getBandenArray addObject:band];
}];
NSLog(@"getBandenArray: %@",getBandenArray);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Error retrieving Banden" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
[alert show];
}];
[queue addOperation:operation];
嗨,戴夫!這看起來非常棒!我已經編輯了我的答案,因爲我想知道我所釀造的解決方案是否可以與您剛纔的建議相比較。我相信AFHTTPClient是更好的選擇,但它是否添加任何東西而不是使用AFJSONRequestOperation? 對不起,這聽起來有點愚蠢,但我剛剛開始與圖書館:)。提前致謝! –
您可以使用JSON方法。我破解了我的例子,但最初獲取圖像,所以http在這種情況下對我更好。抱歉誤導。 – Dave
不是問題!在我閱讀你的答案之後,你幫了我大忙,因爲我只是輕鬆地通過AFHTTPClient管理這些JSON請求!我所做的只是使用AFJSONRequestOperation。兩全其美 ;) –