在iOS中后台更新位置

4

我正在开发一款步行轨迹应用,但遇到了一个问题:当应用在后台时,位置如何更新?我将位置更新和计时器作为绘制地图上的路径。请建议我如何处理。 以下是我的代码:

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{  
    if(!newLocation) return;

    if ((oldLocation.coordinate.latitude != newLocation.coordinate.latitude) &&
        (oldLocation.coordinate.longitude != newLocation.coordinate.longitude))
    {        
      // to  draw path as new location find
        jogPoint = [[JogPoint alloc] initWithCenterCoordinate:newLocation.coordinate];

        [jogPoints addObject:jogPoint];


         if([jogPoints count] >= 5) {

            [self.mapView addOverlay:jogPoint];

            CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:oldLocation.coordinate.latitude longitude:oldLocation.coordinate.longitude];


            CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
            // returns distance in meters
          distnc+=[loc1 distanceFromLocation:loc2] ;
            distanceLabel.text=[NSString stringWithFormat:@"%lf",distnc];

       //  jogInfo.distance += ([loc1 distanceFromLocation:loc2]) * 0.000621371192;

           // jogInfo.eclapsedTime = (CFAbsoluteTimeGetCurrent() - startTime) * 1000 * 60;



        }
    }
 }
2个回答

4

如果您的应用程序处于后台模式,也会像活动状态一样跟踪/更新位置,因此不用担心 :)

只需确保您创建了 CLLocationManager,如下所示:

self.currentLocation = [[CLLocationManager alloc]init];
self.currentLocation.desiredAccuracy = kCLLocationAccuracyHundredMeters;
self.currentLocation.delegate = self;
[self.currentLocation startUpdatingLocation];

编辑:

如果在此处设置了distanceFilter,则您的方法将在特定米数处调用,该值设置在distanceFilter中,否则它会在您的设备移动时更新。

这非常重要,需要在YourProjectName-Info.plist文件中设置/添加Require background mode。值为App Registers for location update

例如:

enter image description here


它会更新定时器,无需在info.plist文件中添加所需的后台模式。 - Arpi
如果distanceFilter是kCLDistanceFilterNone,则didUpdateToLocation会在您移动时自动调用。 - iPatel
@Arpi - 是的,我完全同意 :) - iPatel
1
确保您的distanceFilter未设置,并且不会停止stopUpdatingLocation,这样它将继续调用didUpdateToLocation方法。 - iPatel
我已经完成了。但是我没有得到进一步的处理/代码,如下链接中所讨论的https://dev59.com/3Wkv5IYBdhLWcg3w9lWi - Arpi
显示剩余4条评论

0

您可以使用“显著位置变化”服务来接收位置事件。

此服务提供了显著的省电功能,并提供了足够满足大多数应用程序需求的准确性。它使用设备的蜂窝无线电确定用户的位置并报告该位置的变化,使系统能够比以往更积极地管理功率使用。此服务还能唤醒当前挂起或未运行的应用程序,以提供新的位置数据。

使用“显著位置变化”服务:

创建CLLocationManager类的实例,将委托分配给它,并调用startMonitoringSignificantLocationChanges方法。随着位置数据的可用性,位置管理器会通知其分配的委托对象。如果已经传递了位置更新,则还可以直接从CLLocationManager对象获取最新的位置数据,而无需等待传递新事件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接