2013-08-22 99 views
1

我在使用iOS中的Objective C中的反向地理编码返回城市时遇到问题。我能够在completionHandler中记录城市,但我似乎无法弄清楚如何从另一个函数调用它作为字符串返回。反向地理编码 - 返回本地

城市变量是在头文件中创建的NSString。

- (NSString *)findCityOfLocation:(CLLocation *)location 
{ 

    geocoder = [[CLGeocoder alloc] init]; 
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 

     if ([placemarks count]) 
     { 

      placemark = [placemarks objectAtIndex:0]; 

      city = placemark.locality; 

     } 
    }]; 

    return city; 

} 

回答

7

您的设计是不正确的。

由于您正在执行异步调用,因此无法在方法中同步返回值。

completionHandler是一个将来会被调用的块,因此您必须在调用块时更改代码的结构以处理结果。

例如,您可以使用回调:

- (void)findCityOfLocation:(CLLocation *)location { 
    geocoder = [[CLGeocoder alloc] init]; 
    typeof(self) __weak weakSelf = self; // Don't pass strong references of self inside blocks 
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 
     if (error || placemarks.count == 0) { 
      [weakSelf didFailFindingPlacemarkWithError:error]; 
     } else { 
      placemark = [placemarks objectAtIndex:0]; 
      [weakSelf didFindPlacemark:placemark]; 
     } 
    }]; 
} 

- (void)didFindPlacemark:(CLPlacemark *)placemark { 
    // do stuff here... 
} 

- (void)didFailFindingPlacemarkWithError:(NSError *)error { 
    // handle error here... 
} 

或块(我通常喜欢)

- (void)findCityOfLocation:(CLLocation *)location completionHandler:(void (^)(CLPlacemark * placemark))completionHandler failureHandler:(void (^)(NSError *error))failureHandler { 
    geocoder = [[CLGeocoder alloc] init]; 
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 
     if (failureHandler && (error || placemarks.count == 0)) { 
      failureHandler(error); 
     } else { 
      placemark = [placemarks objectAtIndex:0]; 
      if(completionHandler) 
       completionHandler(placemark); 
     } 
    }]; 
} 

//usage 
- (void)foo { 
    CLLocation * location = // ... whatever 
    [self findCityOfLocation:location completionHandler:^(CLPlacemark * placemark) { 
     // do stuff here... 
    } failureHandler:^(NSError * error) { 
     // handle error here... 
    }]; 
} 
+0

我现在看到的这个,谢谢,我希望我能对此答案投票! – maxmclau

+0

不客气。即使你不能投票的答案,你可以通过选择分数下的勾号接受它;) –

+0

对不起,我不知道只能检查一个单一的答案。固定 – maxmclau

1

反向地址解析请求异步发生,意味着findCityOfLocation方法之前返回completionHandler处理响应。我建议你不要依赖于findCityOfLocation方法返回的城市,但距离completionHandler中执行任何你想要的动作与城市:

- (void)findCityOfLocation:(CLLocation *)location 
{ 

    geocoder = [[CLGeocoder alloc] init]; 
    __weak typeof(self) weakSelf = self; 
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { 

     if ([placemarks count]) 
     { 

      placemark = [placemarks objectAtIndex:0]; 

      weakSelf.city = placemark.locality; 

      // we have the city, no let's do something with it 
      [weakSelf doSomethingWithOurNewCity]; 
     } 
    }];  
}