locationManager未更新位置

时间:2013-06-04 02:03:36

标签: ios objective-c core-location

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

 -(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];
}

1 个答案:

答案 0 :(得分: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只是bootstrap的位置查找:

- (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指定nil代理。