iOS - AFNetworking - 如何在块内返回responseObject

时间:2014-06-10 00:42:21

标签: ios objective-c asynchronous afnetworking objective-c-blocks

我必须使用AFNetworking进行两次API调用,但问题是我需要等待结果才能进一步...

由于参考,我使用Google API Places来获取地点的详细信息。 我有一个地方和一个地方......所以我打两个电话......

问题是,之后我调用我的函数来获取细节,执行进一步......我对块不是很熟悉。如果我明白了,它将在另一个线程中执行代码...

我需要获取FROM和TO细节的函数:

- (IBAction)getDetailsTapped:(id)sender
{
    NSMutableDictionary *googleDetail;
    // Looking for detail for FROM
    googleDetail= [googleAPICaller searchGooglePlaceDetail:[self.from valueForKey:@"reference"]];
    [self.from setValue:[googleDetail valueForKey:@"result"][@"geometry"][@"location"][@"lat"] forKey:@"lat"];
    [self.from setValue:[googleDetail valueForKey:@"result"][@"geometry"][@"location"][@"lng"] forKey:@"lng"];

    // Looking for detail for TO
    googleDetail = [googleAPICaller searchGooglePlaceDetail:[self.destination valueForKey:@"reference"]];
    [self.destination setValue:[googleDetail valueForKey:@"result"][@"geometry"][@"location"][@"lat"] forKey:@"lat"];
    [self.destination setValue:[googleDetail valueForKey:@"result"][@"geometry"][@"location"][@"lng"] forKey:@"lng"];

    [accessibilityAPICaller searchJourney:self.from to:self.destination];
}

我的功能是获取地点的细节:

- (NSMutableDictionary *)searchGooglePlaceDetail:(NSString *)reference
{
    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/details/json?reference=%@&sensor=true&key=%@", reference, kGOOGLE_API_KEY];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    __block NSMutableDictionary *result;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPRequestOperation *operation = [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        result = responseObject;
        NSLog(@"%@", responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation waitUntilFinished];
    return result;
}

我希望确保searchGooglePlaceDetail的执行在完成之前完全完成。 似乎searchJourney之前我已经能够做出先前的指示...... 在我的互联网研究之后,我发现[operation waitUntilFinished];我尝试了它,但看起来执行仍在继续。

3 个答案:

答案 0 :(得分:0)

将第二个调用放在第一个调用的块完成块中:

- (NSMutableDictionary *)searchGooglePlaceDetail:(NSString *)reference
{
    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/details/json?reference=%@&sensor=true&key=%@", reference, kGOOGLE_API_KEY];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    __block NSMutableDictionary *result;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPRequestOperation *operation1 = [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        result = responseObject;
        NSLog(@"%@", responseObject);
        googleDetail = [googleAPICaller searchGooglePlaceDetail:[self.destination valueForKey:@"reference"]];
        [self.destination setValue:[googleDetail valueForKey:@"result"][@"geometry"][@"location"][@"lat"] forKey:@"lat"];
        [self.destination setValue:[googleDetail valueForKey:@"result"][@"geometry"][@"location"][@"lng"] forKey:@"lng"];

        [accessibilityAPICaller searchJourney:self.from to:self.destination];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [operation start];
    return result;
}

在AFNetworking的情况下,块的使用方式与javascript中的回调非常相似。这是在调用返回后执行的代码段。

您有两个可能执行或不执行的块。如果请求成功则成功阻止,如果请求失败则成功失败。

答案 1 :(得分:0)

accessibilityAPICaller类中创建委托协议,然后确保您的视图控制器实现该委托并将其设置为委托本身。

然后,您可以在视图控制器中实现didReceiveJourney:等方法,并在收到数据时调用它。

如果您之前没有实施过委托协议,请here's Apple documentation

答案 2 :(得分:-1)

    You can use this block to get google places and above request also work with this block 

-(void) getGoogleData {            

        // 1

              NSString *string = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=50000&types=%@&sensor=false&key=%@",<latitude>,<longitude>,type,GOOGLE_PLACE_API_KEY];

            NSLog(@"Url string:%@",string);

            NSURL *url = [NSURL URLWithString:string];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];

            // 2
            AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
            operation.responseSerializer = [AFJSONResponseSerializer serializer];

            [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

                [SVProgressHUD dismiss];
                // 3
                NSDictionary *googleData= (NSDictionary *)responseObject;
                NSLog(@"googleData:%@",[googleData JSONRepresentation]);


            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 [SVProgressHUD dismiss];
                // 4
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                                    message:[error localizedDescription]
                                                                   delegate:nil
                                                          cancelButtonTitle:@"Ok"
                                                          otherButtonTitles:nil];
                [alertView show];
            }];

            // 5
            [operation start];


        }