我有两个不同的 UIViewControllers
,它们需要访问用户的 Latitude
和 Longitude
。当 View 出现时,我只需要访问一次该位置。我目前将 LocationManager
存储在应用程序委托(delegate)中,但是 viewDidAppear:
方法加载速度太快,无法找到用户的位置。有谁知道最好的方法吗?谢谢!
最佳答案
我创建了一个共享的 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
只被调用一次。
关于iphone - 在 viewDidAppear 方法中访问用户的位置一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14355654/