两个依赖的异步请求iOS

时间:2012-10-10 07:56:47

标签: ios

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

1 个答案:

答案 0 :(得分: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);
    }];
}