我有两个名为myLocality和myCountry的全局NSString变量......
我已将GeoCode设置如下:
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
finishedGettingLocation = false;
if (newLocation.horizontalAccuracy < 200.0f){
[locationManager stopUpdatingLocation];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
__block NSString *locality;
__block NSString *country;
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks) {
locality = placemark.locality;
country = placemark.ISOcountryCode;
}
}];
do {
} while ([geoCoder isGeocoding]);
myLocality = locality;
myCountry = country;
finishedGettingLocation = true;
}
}
我的后台主题如下:
- (void) doWork
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
finishedGettingLocation = false;
dispatch_async(dispatch_get_main_queue(), ^{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
[locationManager startUpdatingLocation];
});
int counter = 0;
do {
[NSThread sleepForTimeInterval:.1];
counter ++;
if (counter % 200 == 0){
dispatch_async(dispatch_get_main_queue(), ^{
Toast *oToast = [Toast toastWithMessage:@"Gps pin-pointing works faster if you are outside"];
[oToast showOnView:self.view];
});
counter = 0;
}
} while (!finishedGettingLocation);
NSLog(@"%@", myCountry); // this is where I am trying to print
NSLog(@"%@", myLocality); // this is where I am trying to print
});
}
(是的,我知道这是非常草率的代码,但是,meh .. xD)
现在,我无法弄清楚当我在其他地方的代码中记录它们时,为什么这些返回null。
但是,当我将登录上面的for
,即NSLog(@"%@", placemark.locality)
我得到正确的值,或者至少我得到一个值。
如何从placemark
?
答案 0 :(得分:1)
这些变量在哪里宣布?
如果您在正在进行地理编码的班级中设置了myLocality
和myCountry
静态,那么其他班级一旦设置就可以访问它们。
另一种方法是创建一个@protocol
并让类希望地理编码的结果在完成后接收回调。
答案 1 :(得分:1)
在AppDelegate中创建地区和国家/地区属性,并随时随地访问它们。
// Set values
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.locality = @"Some Area";
appDelegate.country = @"Some Country";
// Get values
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *myLocality = appDelegate.locality;
NSString *myCountry = appDelegate.country;
您还可以创建一个专用的单例类,并使用它而不是使用app delegate。
答案 2 :(得分:0)
do while
循环的条件更改为myCountry == null
并且它工作了=]。谢谢你的帮助。