【问题标题】:Can't get CLLocationManager to stop tracking无法让 CLLocationManager 停止跟踪
【发布时间】:2013-12-05 20:36:58
【问题描述】:

我有一个启动 CLLocationManager 实例的类。目的是使用它在应用程序启动时获得体面的一次性修复,然后在此期间停止定位服务(或直到满足需要新修复的其他条件......但该部分尚未编写)。

出于某种原因,即使我调用了 [stopUpdatingLocation],我的应用似乎仍然无限期地保持位置服务处于活动状态,无论是否在后台。正如预期的那样,我的代表不再收到更新,但箭头停留在状态栏上。我关闭了所有其他应用的定位服务以确认我的应用是罪魁祸首,然后手动终止了我的应用(它立即关闭了箭头)。

我的代码基于您在 Apple 文档中找到的内容,并为我的目的添加了一些内容。我已经阅读了所有相关的 Apple 文档,但无法弄清楚我做错了什么。关于该主题的所有其他答案都针对使用 MKMapView 并忘记将“showUserLocation”设置为 NO 的人......我根本没有使用 MKMapView,所以这不是我的问题。有没有搞错。为什么它不会死?

(_locationManager 当然是我的 CLLocationManager 实例)。

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:
(NSArray*)locations
{
    CLLocation* lastLocation = [locations lastObject];

    // Ignore old (cached) location
    NSDate *date = lastLocation.timestamp;
    NSTimeInterval howRecent = [date timeIntervalSinceNow];

    if (abs(howRecent) > 30.0)
    {
        DLog(@"Ignoring cached fix");
        return;
    }

    // Wait for better fix if we have GPS
    if (lastLocation.horizontalAccuracy > 60 && _GPSEnabled)
    {
        DLog(@"Ignoring inaccurate fix on GPS-enabled device");
        return;
    }

    // Accept mediocre fix if we don't have GPS
    if (lastLocation.horizontalAccuracy < 300 && _GPSEnabled == NO)
    {
        _hasPos = YES;
        _lastPos = lastLocation.coordinate;
        DLog(@"Best fix we're likely to get without GPS: %f %f", _lastPos.latitude,
       _lastPos.longitude);
        [self stopTracking];
        return;
    }

    // If we have GPS, accept a fix with <60m accuracy
    _hasPos = YES;
    _lastPos = lastLocation.coordinate;
    DLog(@"Geolocator has good fix: %f %f", _lastPos.latitude, _lastPos.longitude);
    [self stopTracking];    
}

-(void)stopTracking
{
    DLog(@"Stopped updating locations");
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
}

【问题讨论】:

    标签: ios cllocationmanager


    【解决方案1】:

    终于在另一个问题中找到了答案……在这里重印,因为我花了一段时间才偶然发现它。

    我不得不这样称呼:

    [_locationManager stopMonitoringSignificantLocationChanges];
    

    尽管我一开始从未调用 startMonitoringSignificantLocationChanges,但似乎我不得不“取消调用”它……奇怪的是它以这种方式工作,但一旦我添加了该行,定位服务就会立即关闭。希望这对其他人有帮助。

    【讨论】:

    • 很好奇您是如何开始位置更新的。您使用的是 startUpdatingLocation 还是 startMonitoringSignificantLocationChanges?
    • 我只调用过 startUpDatingLocation...从未打算使用重大更改服务。这就是为什么我很惊讶我需要停止它......在我看来它没有按预期工作,而且我在文档中没有看到任何提及。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多