ios - 在 iOS 8 中的计时器/定期更新背景中的位置

标签 ios core-location

如果应用程序处于后台状态或前台状态,我希望每 5 分钟更新一次用户的位置。这是一款对位置非常敏感的应用程序,因此始终了解位置非常重要。

在 SO 上有很多与此问题相关的答案,但其中很多都涉及 iOS 6 及更早版本。在 iOS 7 之后,很多后台任务都发生了变化,我很难找到在后台实现定期位置更新的方法。

最佳答案

您需要使用 CoreLocation 的委托(delegate)。一旦你得到一个坐标,停止 CoreLocation,设置一个定时器在 5 分钟后再次启动它。

在 iOS 8 中,您需要为 NSLocationWhenInUseUsageDescription 和/或 NSLocationAlwaysInUseDescription 设置一个 plist 条目。

Apple 文档非常清楚地说明了如何执行所有这些操作。

-(void)startUpdating{
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager startUpdatingLocation];

}

-(void)timerFired{
    [self.timer invalidate];
    _timer = nil;
    [self.locationManager startUpdatingLocation];
}

// CLLocationDelegate
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations{
    if(locations.count){
        // Optional: check error for desired accuracy
        self.location = locations[0];
        [self.locationManager stopUpdatingLocation];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:60 * 5 target:self selector:@selector(timerFired) userInfo:nil repeats:NO];
    }
}

关于ios - 在 iOS 8 中的计时器/定期更新背景中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25980778/

相关文章:

ios - 在 iOS 中 WKWebView 的后台历史记录中显示带有父 URL 的子 URL

ios - 获取位置后无法更新标签

隐藏 View 时的 iOS 布局更改

iphone - ios iphone 开发中的 Relativelayout 或 LinearLayout?

ios - SwiftUI:动态设置图像的大小

iOS 8自定义闹钟使用uilocalnotification并在手机静音时在后台播放声音

ios - 使多个对象成为另一个对象的委托(delegate)的最佳方法是什么?

iphone - 将 lat long 分配给 CLLocation 给出错误不接受任何格式

ios - 我如何确定 iPhone CoreLocation 是否使用卫星或蜂窝塔三角测量来查找当前位置?

ios - 我想创建一个标签来跟踪访问 View Controller 的次数