对于我的应用程序,我必须连接到两个返回 JSON 的 Web 服务。
我首先使用 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];