2

I'm trying to do simple thing. I want to find an array of addresses and show it on map. But then I need to pass data to another view.

The problem is: I need to pass data from dictionary which contains address, so, I need to know which exactly address was found. Request is async and main-thread only so I can't understand what address was found right now.

Sorry if I'm talking not clear.

   for (NSDictionary *dic in adresses) {

            MKLocalSearch *search = [[MKLocalSearch alloc]initWithRequest:request];
            request.naturalLanguageQuery = [dic valueForKey:@"adress"];
            [search startWithCompletionHandler:^(MKLocalSearchResponse
                                                 *response, NSError *error) {


                if (response.mapItems.count == 0){

                    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
                    [dictionary setValue:request.naturalLanguageQuery forKey:@"realadress"];
                    [dictionary setValue:@"empty" forKey:@"itemname"];
                    [adressesonmap addObject:dictionary];
                    [array addObject:@"empty"];

//HERE I NEED TO KNOW WHICH ADRESS MAPKIT TRIED TO FIND!!!
                }
                else{
                    for (MKMapItem *item in response.mapItems)
                    {
                        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
                        [dictionary setValue:request.naturalLanguageQuery forKey:@"realadress"];
                        [dictionary setValue:item.name forKey:@"itemname"];
                        [adressesonmap addObject:dictionary];

                        [matchingItems addObject:item];
                        MKPointAnnotation *annotation = [[MKPointAnnotation alloc]init];
                        annotation.coordinate = item.placemark.coordinate;
                        annotation.title = request.naturalLanguageQuery;
//HERE I NEED TO KNOW WHICH ADRESS MAPKIT TRIED TO FIND!!!

     // here I'me trying to get address, which I tried to find before in request, but it's always one of them (from request.naturalLanguageQuery)

                        [_mapView addAnnotation:annotation];
                        }
                    }
                }];

            }
Pang
  • 9,564
  • 146
  • 81
  • 122
Lippy Flo
  • 31
  • 3

1 Answers1

1

As I understood, you need to know what Address was found by async request. You are using block to obtain a callback, so you can just use variables from outer scope in the block, it will capture the reference until finishes.

NSArray *adresses = @[
        @{@"adress":@"Kyiv, Gorkogo 17"},
        @{@"adress":@"New York"}
];

for (NSDictionary *dic in adresses) {
    MKLocalSearchRequest *request = [MKLocalSearchRequest new];
    request.naturalLanguageQuery = [dic valueForKey:@"adress"];
    MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request];
    [search startWithCompletionHandler:^(MKLocalSearchResponse
                                         *response, NSError *error) {
        NSLog(@"\n\n\n+++++\nFound address: %@  response items:%@ ",dic[@"adress"], response.mapItems);
    }];

}
Alexander Tkachenko
  • 3,221
  • 1
  • 33
  • 47
  • Thank's for your answer! But I tried this variant also... In this variant I got not right addresses and can't understand why. For the best example: in NSLog it shows addresses that weren't found. – Lippy Flo May 26 '15 at 15:07
  • Maybe I misunderstood something. What is your expected and actual behavior on your code? Please, add more details in the answer – Alexander Tkachenko May 26 '15 at 15:10
  • Как я понимаю, можно по-русски? – Lippy Flo May 26 '15 at 15:14
  • Ситуация такая. Я даю на вход словарь с адресами. Он поочередно отправляет запрос, я получаю координаты, все здорово. Но мне надо связать метки с другой информацией в словаре, соответственно, надо понять какой именно он нашел адрес из словаря. Когда я использую предложенный Вами метод, он выдает совсем не тот адрес по которому ищет (видимо нитка уже пошла дальше, а инфа в блоке осталась). Честно говоря, не особо понимаю почему так происходит.... – Lippy Flo May 26 '15 at 15:18
  • Александр, Вы меня выручили! – Lippy Flo May 26 '15 at 15:27
  • Я так понимаю возможно проблема в Вашем request, который один на весь цикл, и вы его модифицируете, и он может как-то влияет :) Не за что, удачи! – Alexander Tkachenko May 26 '15 at 15:28