gpt4 book ai didi

ios - 阻塞直到 reverseGeocode 返回

转载 作者:行者123 更新时间:2023-11-28 20:06:03 27 4
gpt4 key购买 nike

我正在尝试从坐标中找到用户的位置以保存到我的数据库中。

要查找位置名称,我正在使用 reverseGeocode。然而,由于它是一个 block 方法,我的 self.locationName 将返回(并保存为 nil)到数据库中。所以我试图找到解决问题的方法,并尝试使用信号量将以下解决方案组合在一起,尝试阻止直到我得到一个可以保存的 locationName,但是当按下保存按钮时应用程序只是挂起。我应该以这种方式解决这个问题还是有更好的方法?

 dispatch_semaphore_t semaphore;

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

NSLog(@"Finding address");
if (error) {
NSLog(@"Error %@", error.description);
} else {
CLPlacemark *placemark = [placemarks lastObject];
self.locationName = [NSString stringWithFormat:@"%@", ABCreateStringWithAddressDictionary(placemark.addressDictionary, NO)];
dispatch_semaphore_signal(semaphore);
}
}];
}



-(NSString *)findLocation:(CLLocation *)startingLocation
{
semaphore = dispatch_semaphore_create(0);
[self reverseGeocode:startingLocation];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); //should maybe timeout
return self.locationName;
}

最佳答案

你的想法全错了。这不是异步代码的工作方式。在代码返回之前,不要 阻塞。只需启动代码即可开始反向地理编码,然后完成。现在,当反向地理编码完成时,它会给你回电,你可以用返回的信息做任何你想做的事。这就是完成处理程序的全部要点:在反向地理编码完成之前它不会运行。

只需摆脱信号量,让事情异步发生即可。这是一个没有辅助方法的完整示例:

CLLocation* loc = userLocation.location;
[geo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error)
{
if (placemarks) {
CLPlacemark* p = [placemarks objectAtIndex:0];
NSLog(@"%@", p.addressDictionary); // do something with address
}
}];

正如您已经被告知的那样,如果您真的想从另一个方法调用它然后做进一步的事情,那么将一个 block 传递给这个方法并在完成处理程序中调用该 block 。这意味着您传递的 block 是将在地理编码完成时运行的代码,这正是您想要的 - 没有信号量,也没有卡住应用程序。

卡住应用程序是一种糟糕的形式,如果您这样做时间过长,WatchDog 会杀死您的应用程序。只是不要这样做。

关于ios - 阻塞直到 reverseGeocode 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22079079/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com