iOS:当我尝试通过点击获取 CLLocation 时,大部分时间都有 "big"滞后

标签 ios objective-c cllocationmanager

我首先使用 CoreLocation 框架。我有一个表格,通过单击按钮应该添加一个新位置,并且应该始终显示和更新到表格中所有条目的距离。这就是为什么我有一个 BOOL saveNewLocation,它在单击按钮时设置为 Yes。因为更新需要始终在后台发生,但是当单击按钮时,只会添加一个新条目。

目前我的 viewDidLoad 中有这个:

self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager startUpdatingLocation];

这是我的委托(delegate)方法:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    self.currentLocation = newLocation;
    if(self.saveNewLocation){
       [PointOfInterest addPointOfInterest:newLocation withAddress:@"" andNotes:@"" inManagedObjectContext:self.cdh.context];
        self.saveNewLocation = NO;
    }
    [self updateAllDistances];
}

这是我的按钮:

- (IBAction)addLocationClicked:(id)sender {
    self.saveNewLocation = YES;
}

但是现在的问题是,当你点击这个按钮的时候,有时候会出现很大的卡顿,没有任何反应。有时会立即添加一个新位置。如何避免这种延迟并通过点击立即添加新位置?

最佳答案

位置管理器委托(delegate)的更新调用之间的时间间隔是可变的,因此您遇到的行为是预料之中的。

CLLocationManager 有一个名为 location 的属性,它返回用户最后已知的位置(如果您从未在应用程序中使用过位置管理器,则为 nil)。

与其等待 LocationManager 更新,不如获取用户最后已知的位置:

- (IBAction)addLocationClicked:(id)sender {
    CLLocation *location = self.locationManager.location;
    if (location && [NSDate timeIntervalSinceReferenceDate] - location.timeStamp.timeIntervalSinceReferenceDate < 60 * 10){
    //Do something with the location if the location manager returns a location within the last 10 minutes
    } else {
       self.saveNewLocation = YES;
    }
}

如果应用程序从未请求过它的位置,您可能会得到 nil,在这种情况下,您将不得不等待 locationManager 更新。但除此之外,您可以只获取最后已知的位置。您还可以通过检查位置对象上的时间戳来检查该位置最近是否更新。

您可能还想设置一个状态标志,指示应用程序应该在首次使用位置管理器时等待位置更新。当您第一次启动 LocationManager 时,您无法真正了解该位置的最新信息。但是一旦管理器开始更新委托(delegate),您就可以合理地确定 location 管理器拥有一个相当最新的位置。

关于iOS:当我尝试通过点击获取 CLLocation 时,大部分时间都有 "big"滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151882/

相关文章:

ios - 如何将 `accessibilityLabel` 添加到 `UIAlertView` 按钮?

ios - NSPredicate 和丹麦字母 å 给出了错误的结果

html - 粗体 `<b>` 标签和斜体 `<i>` 标签不适用于自定义字体系列

ios - 通过 UITableView 保存到 SQLITE3 时的奇怪行为

ios - 如何从 viewDidLoad 调用 "didUpdateLocation"方法?

ios - 将 userLocation 打印到 textLabel

ios - 在 iOS 中解析 XML?

ios - 标签栏 Controller 应该如何集成到导航 Controller 工作流程中?

objective-c - 将 .xib 文件添加到 UIViewController 子类?

ios - 我什么时候应该停止更新位置管理器?