2

对于我的应用程序,我必须连接到两个返回 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];
4

1 回答 1

4

AFNetworking 类将允许您创建一堆操作,然后将它们全部交给处理。您添加一些代码以在每个单独请求的成功/失败和/或所有请求都已处理时发生。

这是您可能会做的事情的概述。我将把细节、实际比较和错误处理留给你想象。:)

-(void)fetchAllTheData {
    NSMutableArray * operations = [NSMutableArray array];
    for (NSString * url in self.urlsToFetchArray) {
        [operations addObject:[self operationToFetchSomeJSON:url]];
    }
    AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:[PREFS objectForKey:@"categoryUrlBase"]]];
    [client enqueueBatchOfHTTPRequestOperations:operations
                                  progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
                                      NSLog(@"Finished %d of %d", numberOfFinishedOperations, totalNumberOfOperations);
                                  }
                                completionBlock:^(NSArray *operations) {
                                    DLog(@"All operations finished");
                                    [[NSNotificationCenter defaultCenter] postNotificationName:@"Compare Everything" object:nil];
                                }];
}

-(AFHTTPRequestOperation *)operationToFetchSomeJSON:(NSString*)whichOne {
    NSURL * jsonURL = [NSURL URLWithString:whichOne];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:jsonURL];
    [request setHTTPShouldHandleCookies:NO];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"My data = %@", operation.responseString); // or responseData
        // Got the data; save it off.
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"Error downloading: %@  %@", whichOne, error);
    }];
    return operation;
}

希望有帮助。

于 2013-01-22T19:22:58.473 回答