2013-06-04 97 views
0

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

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

回答

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的代表。