我创建了一个共享的LocationManager。然后startUpdatingLocation 和stopUpdatingLocation 在你得到回调之后。
这是我使用的代码:
在您的appDelegate 中添加以下方法:
+ (NHAppDelegate *)sharedDelegate
{
return (NHAppDelegate *)[[UIApplication sharedApplication] delegate];
}
并使 LocationManager 可用:
@property (nonatomic, strong) CLLocationManager *locationManager;
然后在你的 UIViewController 中你可以这样做:
[NHAppDelegate sharedDelegate].locationManager.delegate = self;
[[NHAppDelegate sharedDelegate].locationManager startUpdatingLocation];
然后我使用以下代码获取位置并在 UILabel 中显示。
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
[self loadPositionWithLocation:newLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations objectAtIndex:0];
[self loadPositionWithLocation:location];
}
-(void)loadPositionWithLocation:(CLLocation *)newLocation
{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:
^(NSArray* placemarks, NSError* error){
if ([placemarks count] > 0)
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *thoroughfare = placemark.thoroughfare;
NSString *subThoroughfare = placemark.subThoroughfare;
NSString *postalCode = placemark.postalCode;
NSString *locality = placemark.locality;
if( thoroughfare == nil ) { thoroughfare = @""; }
if( subThoroughfare == nil ) { subThoroughfare = @""; }
if( postalCode == nil ) { postalCode = @""; }
if( locality == nil ) { locality = @""; }
NSString *addressString = [NSString stringWithFormat:@"%@ %@\n%@ %@", thoroughfare, subThoroughfare, postalCode, locality];
self.positionLabel.text = addressString;
[[NHAppDelegate sharedDelegate].locationManager stopUpdatingLocation];
}
}];
}
重要的是最后一行 stopUpdatingLocation 所以 LocationManager 只被调用一次。