-2

我在 JSONParser 类中有两个请求(A&B)。B 依赖于 A 的响应。两个请求都返回 JSON 响应。使用这两个响应将创建一个对象 C,然后我想将 C 返回给视图控制器。

4

1 回答 1

0

这是我的例子。这是非常初步的,但你可以弄清楚如何......你还需要添加错误检查。

typedef void(^ResultBlock)(id data);

- (NSDictionary *)dataFromURL:(NSString *)url {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLResponse *response;
    NSError *error;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSDictionary* document = [NSJSONSerialization
                              JSONObjectWithData:responseData //1
                              options:kNilOptions
                              error:&error];
    return document;
}

- (void)getSomeDataWithCompletion:(ResultBlock)completion {

    NSOperationQueue *q = [[NSOperationQueue alloc] init];
    [q addOperation:[NSBlockOperation blockOperationWithBlock: ^ {
        NSDictionary *response1 = [self dataFromURL:@"server/api1"];

        id result = nil;
        if (response1) {
            NSDictionary *response2 = [self dataFromURL:[NSString stringWithFormat:@"%@/%@", @"server/api2", [response1 objectForKey:@"someParameter"]]];
            result = [response2 objectForKey:@"iFindThisObject"];
        }
        completion(result);
    }]];
}

- (void)performRequest {
    [self getSomeDataWithCompletion:^(id data) {
        NSLog(@"Result %@", data);
    }];
}
于 2012-10-10T08:22:54.473 回答