iphone - CLLocationManager 初始化并调用按钮

标签 iphone ios geolocation core-location cllocationmanager

我希望我的应用程序在用户点击按钮时获取当前位置。我在 init 方法中初始化 locationManager 对象。

第一个问题:如果我每次按下按钮时都需要当前位置,这样好吗?或者我应该在 viewDidLoad 中初始化它吗?

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self)
    {
        // Create location manager object
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;

        // Best accuracy as posibble
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    }
    return self;
}

在我的委托(delegate)方法中,一旦获得我的currentLocation,我就会stopUpdatingLocation

// Delegate method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray        
*)locations   
{
    CLLocation *currentLocation = [locations lastObject];

    [locationManager stopUpdatingLocation];
}

这里我使用按钮startUpdatingLocation:

- (IBAction)getCurrentLocation:(id)sender
{
    [locationManager startUpdatingLocation];
}

第二个问题是:当我第一次按下按钮时,我得到了正确的位置,但是当我在模拟器中更改位置并再次按下时,它显示第一个位置。再次,当我按下按钮时,它会显示正确的按钮。我尝试在每次按下按钮时初始化 locationManager 但它也不起作用。

我在其他帖子上读到,这是因为位置缓存或类似的原因。如何删除该缓存?因为无论如何我都会将该位置存储在数据库中的其他位置,所以我不需要旧的位置..

最佳答案

问题 1:我应该在 init 中还是在 viewDidLoad 中初始化位置管理器

我会选择viewDidLoad,只是因为这样你可以确保所有依赖项都已加载。

问题 2:用户位置未更新。

用户位置没有改变,因为您在第一次接收位置信息后停止监听位置更新:

[locationManager stopUpdatingLocation];

但是当用户按下 getCurrentLocation 按钮时,您会再次开始监听。 如果您愿意,您仍然可以采用这种方法,但我会在 getCurrentLocation 操作中设置一个标志,以便在找到新位置时更新 UI。

示例:

// Delegate method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray        
*)locations   
 {
     CLLocation *currentLocation = [locations lastObject];

     [locationManager stopUpdatingLocation];

     if (self.updateUIOnNextLocation) {
         [self updateUIWithLocation:currentLocation];
         self.updateUIOnNextLocation = NO;
     }
}

...

- (IBAction)getCurrentLocation:(id)sender
{
     self.updateUIOnNextLocation = YES;
     [locationManager startUpdatingLocation];
}

关于iphone - CLLocationManager 初始化并调用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16071550/

相关文章:

iphone - 输入电子邮件 ID 时自动完成电子邮件 ID 的建议

iphone - 导航栏下方的工具栏(?) - iPhone

ios - 如何以编程方式在 UITableViewCell 中添加 UIView?

ruby-on-rails - ruby 地理编码 : Make a model 'geocoded' when latitude and longitude already exist from other source?

php - 获取 Laravel 坐标半径范围内的用户

redis - 使用大列表的地理定位数据,用纬度/经度标记巨大的元素列表

iphone - 在应用程序中购买 SKProductsRequest 在 ios 5 中崩溃我的应用程序

iphone - iOS - 使用 TPKeyboard 避免在两个 ScrollView 上,它们相互影响

ios - TableView 单元格行高不起作用

ios - 具有 UIPicker 性能的下拉选择