2013-06-04 133 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的代表。