ios - 反向地址解析-返回位置

标签 ios objective-c core-location

我无法在iOS上的Objective C中使用反向地理编码来返回城市。我可以在completionHandler中记录城市,但是如果从另一个函数调用它,我似乎无法弄清楚如何将其作为字符串返回。

city变量是在头文件中创建的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;

}

最佳答案

您的设计不正确。

由于您正在执行异步调用,因此无法在方法中同步返回值。
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...
   }];
}

关于ios - 反向地址解析-返回位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18384302/

相关文章:

ios - 应用因持久存储创建崩溃而被拒绝

objective-c - NSOpenPanel 和检测到泄漏的观察者

iphone - UITabBar 识别纵向或横向方向

iphone - 停止 MKMapview 的用户位置更新(蓝点)

ios - 将 Double 转换为 CLLocationDegrees [SWIFT]

ios - 使用 View Controller Containment 的缺点

更改方向后,iOS8 无法重新调整模态表单的大小

objective-c - 分配字符串时发送到实例的无法识别的选择器

ios - 对于键 'CIAttributeTypeRectangle.',此类不符合键值编码

iphone - 为什么要在 init 方法中调用 autorelease 来定义 iVar?