0

我正在使用此代码获取位置,使用模拟器,但它没有给我任何输出。如果有人建议我解决这个问题或更好的替代解决方案。\

 -(void)viewDidAppear:(BOOL)animated
 {
_locationManager.delegate=self;
 [_locationManager startUpdatingLocation];
[self.geoCoder reverseGeocodeLocation: _locationManager.location completionHandler:
 ^(NSArray *placemarks, NSError *error) {
      if (error) {
         return;
     }

     if (placemarks && placemarks.count > 0)
     {
         CLPlacemark *placemark = placemarks[0];

         NSDictionary *addressDictionary =
         placemark.addressDictionary;

         NSString *address = [addressDictionary
         objectForKey:(NSString *)kABPersonAddressStreetKey];
         NSString *city = [addressDictionary
                           objectForKey:(NSString *)kABPersonAddressCityKey];
         NSString *state = [addressDictionary
                            objectForKey:(NSString *)kABPersonAddressStateKey];
         NSString *zip = [addressDictionary
                          objectForKey:(NSString *)kABPersonAddressZIPKey];

         NSString *Countrynsme = [addressDictionary
                                  objectForKey:(NSString *)kABPersonAddressCountryKey];

         _requestorAddressText.Text = address;
         _requestorCityText.text = city;
         _requestorPostalText.text = zip;
         _CountryrequestorText.text = Countrynsme;
         _requestorStateText.text = state;
         }

  }];

 [_locationManager stopUpdatingLocation];
}
4

1 回答 1

3

CLLocationManager 是一个异步 API。在对位置进行地理编码之前,您需要等待 CLLocationManager 的结果。

使用CLLocationManagerDelegate开始监听位置管理器更新

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    NSTimeInterval interval = [newLocation.timestamp timeIntervalSinceNow];
    if (interval < 0) {
        interval = -interval;
    }        
    // Reject stale location updates.
    if (interval < 30.0) {
        // Start geocoding
        [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
             // Use geocoded results
             ...
        }];
    }
    // If you're done with getting updates then do [manager stopUpdatingLocation]
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    // Handle error. Perhaps [manager stopUpdatingLocation]
}

然后viewDidAppear只是引导的位置查找:

- (void)viewDidAppear {
    // PS: You're missing a call to [super viewDidAppear]
    [super viewDidAppear];
    // Start lookup for location
    _locationManager.delegate=self;
    [_locationManager startUpdatingLocation];
}

PS:在 dealloc 中不要忘记停止更新位置,取消地理编码并将 locationManager 的代表归零。

于 2013-06-04T02:07:54.633 回答