【问题标题】:GMSGeoCoder reverseGeocodeCoordinate: completionHandler: on background threadGMSGeoCoder reverseGeocodeCoordinate:completionHandler:在后台线程上
【发布时间】:2016-02-16 13:33:06
【问题描述】:

我需要从 2 个坐标中获取城市名称(我正在使用 GMSGeoCoder -reverseGeocodeCoordinate: completionHandler: 方法),然后对对象进行比较。

问题是该方法在后台线程上运行(而不是在主线程中),当我尝试比较(使用if 语句)对象(userCitystoreCity-两者都是NSString ) 仍然为零。

我的代码:

//Checking user's city
        __block NSString *userCity;
        [[GMSGeocoder geocoder]reverseGeocodeCoordinate:self.locationManager.location.coordinate completionHandler:^(GMSReverseGeocodeResponse *response, NSError *error) {
            if (error) {
                NSLog(@"%@",[error description]);
            }
            userCity=[[[response results] firstObject] locality];
        }];
        //Checking store's city
        __block NSString *storeCity;
        [[GMSGeocoder geocoder]reverseGeocodeCoordinate:arounder.radiusCircularRegion.center completionHandler:^(GMSReverseGeocodeResponse *response, NSError *error) {
            if (error) {
                NSLog(@"%@",[error description]);
            }
            arounderCity=[[[response results] firstObject] locality];
        }];
        if ([userCity isEqualToString:arounderCity]) {
            return YES;
        }

有什么想法吗?谢谢!

【问题讨论】:

  • 是的,等待块然后继续!
  • @Daij-Djan 这基本上就是我想做的,但我该怎么做呢?可以给我一个代码示例吗?
  • 我写了一个。请注意我是内联写的,可能有较小的错别字,但它会给你逻辑

标签: ios objective-c google-maps-sdk-ios


【解决方案1】:

在异步任务完成后重组您的代码以继续:

这还有一个好处是你不会主动等待东西并阻塞主线程

例如:

- (void)checkCitiesWithCompletionBlock:(void (^)(BOOL same))
    //Checking user's city
    [[GMSGeocoder geocoder]reverseGeocodeCoordinate:self.locationManager.location.coordinate completionHandler:^(GMSReverseGeocodeResponse *response, NSError *error) {
        if (error) {
            NSLog(@"%@",[error description]);
        }
        id userCity=[[[response results] firstObject] locality];

        //Checking store's city
        [[GMSGeocoder geocoder]reverseGeocodeCoordinate:arounder.radiusCircularRegion.center completionHandler:^(GMSReverseGeocodeResponse *response, NSError *error) {
            if (error) {
                NSLog(@"%@",[error description]);
            }
            id arounderCity=[[[response results] firstObject] locality];

            same ([userCity isEqualToString:arounderCity]);
        }];
    }];
}   

【讨论】:

  • 我将在返回 BOOL 的函数上调用 -checkCitiesWithCompletionBlock:,我应该在完成之外返回什么?
  • 如果你愿意.. 我不建议这样做.. 等待块完成。但是外部 api 也应该是异步的 IMO。如何等待我之前也在 SO 上回答过的问题,这可能会对您有所帮助:)
猜你喜欢
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-26
  • 2011-02-14
相关资源
最近更新 更多