iphone - 在 viewDidAppear 方法中访问用户的位置一次

标签 iphone ios objective-c core-location locationmanager

我有两个不同的 UIViewControllers,它们需要访问用户的 LatitudeLongitude。当 View 出现时,我只需要访问一次该位置。我目前将 LocationManager 存储在应用程序委托(delegate)中,但是 viewDidAppear: 方法加载速度太快,无法找到用户的位置。有谁知道最好的方法吗?谢谢!

最佳答案

我创建了一个共享的 LocationManager。然后 startUpdatingLocationstopUpdatingLocation 在你得到一个回调之后。

这是我使用的代码:

在您的 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/

相关文章:

iphone - objective-c : Using UIImage for Stroking

iPhone xcode - 从多个 View Controller 控制音频的最佳方式

ios - trailingSwipeActionsConfigurationForRowAt 不能稳定工作

ios - 使搜索栏和 uisearchDisplayController 看起来像普通的输入字段

javascript - 在 tableViewRow 中交换图像

ios - 为什么使用强大的属性来保存选择器 View

ios - iPhone 6 Plus 中的搜索图标变形 - 被压成蛋形

iphone - 核心数据和核心位置

objective-c - 为 hello world 启动什么样的项目重要吗?

ios - 即使不支持横向,也以横向模式显示 UIImage