当app在后台时,将纬度和经度发送到服务器

时间:2016-05-12 14:02:05

标签: ios background nstimer core-location

我已经经历了这么多链接,即使在那之后我还没有找到适当的解决方案来获取经度和经度。

Periodic iOS background location updates

iOS long-running background timer with "location" background mode

我试过一些链接和论坛,但它只工作了3分钟,然后应用程序根本没有更新用户位置。

tabstop - 1

3 个答案:

答案 0 :(得分:10)

确定。

经过3天的挣扎之后,即使在3分钟之后应用程序处于后台,它也可以用于发送经度和经度。

我检查了我的应用程序,在后台连续发送了超过一小时的lat。

它至少可以帮助一些人。

首先请在pList中添加以下两个键。

 1.NSLocationAlwaysUsageDescription
 2.NSLocationWhenInUseUsageDescription

Bothe是字符串,你可以给出任何价值。

然后请打开后台获取并检查项目部分功能下的位置更新。

然后导入Corelocation框架并在下面添加代码。

locationManager是一个全局变量。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
 //create CLLocationManager variable
locationManager = [[CLLocationManager alloc] init];
//set delegate
locationManager.delegate = self;

app = [UIApplication sharedApplication];
// This is the most important property to set for the manager. It ultimately determines how the manager will
// attempt to acquire location and thus, the amount of power that will be consumed.

if ([locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [locationManager setAllowsBackgroundLocationUpdates:YES];
}
locationManager.desiredAccuracy = 45;
locationManager.distanceFilter = 100;
// Once configured, the location manager must be "started".
[locationManager startUpdatingLocation];
}

 - (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

[locationManager stopUpdatingLocation];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
locationManager.pausesLocationUpdatesAutomatically = NO;
locationManager.activityType = CLActivityTypeAutomotiveNavigation;
[locationManager startUpdatingLocation];
 }

 - (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.


[locationManager stopUpdatingLocation];

__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    bgTask = UIBackgroundTaskInvalid;
}];

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0
                                              target:self
                                            selector:@selector(startTrackingBg)
                                            userInfo:nil
                                             repeats:YES];


 }

-(void)startTrackingBg {

[locationManager startUpdatingLocation];
 NSLog(@"App is running in background");
}
 //starts automatically with locationManager
  -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
latitude=newLocation.coordinate.latitude;
longitude=newLocation.coordinate.longitude;
NSLog(@"Location: %f, %f",newLocation.coordinate.longitude, newLocation.coordinate.latitude);
 }

答案 1 :(得分:0)

您需要参考此苹果文档handling location events in the background

您需要在Xstrong项目的功能中的后台模式中启用位置更新

标准位置服务 不会在后台模式下工作,因此您必须使用重大更改位置服务或访问服务

使用此代码进行

locationManager.delegate = self
locationManager.startMonitoringSignificantLocationChanges()

启用重大更改位置服务。

答案 2 :(得分:0)

在桑托斯(Santos)答案的基础上,它具有完成背景定位工作的大多数重要步骤,我已经澄清并纠正了一些细节。

项目设置

您应该将这些键添加到Xcode Target Info 属性列表中。确保为它们每个添加有效的描述,否则您的应用可能无法通过批准。

  • NSLocationAlwaysUsageDescription
  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysAndWhenInUseUsageDescription

enter image description here

接下来,在目标功能中,打开后台模式并检查位置更新背景获取。位置更新将在后台启用位置,而后台抓取将使您能够在后台使用网络。 enter image description here

开始监视

首先创建一个CLLocationManager实例,对其进行配置并打开后台更新,然后启动它。尽管下面的代码使用最常用的功能startUpdatingLocation来获取位置,但是还有其他几种服务可以使用。选择最合适的服务很重要,因为这会严重影响电池使用量,并且是否会由iOS重新启动该应用也会对应用程序产生影响。有关更多信息,请参见下文。

// Declare as properties in your class
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) CLLocation *lastLocation;

// Call to start
- (void)initializeAndStartLocationService {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;

    // Must be set for background operation
    self.locationManager.allowsBackgroundLocationUpdates = YES;

    // Optional configuration
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.pausesLocationUpdatesAutomatically = YES;
    self.locationManager.showsBackgroundLocationIndicator = YES;

    // Authorize - the lazy way
    [self.locationManager requestAlwaysAuthorization];

    // Start the standard location service, there are others
    [self.locationManager startUpdatingLocation];
}

// Delegate method that will receive location updates
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    // Keep the last received location
    self.lastLocation = [locations lastObject];

    NSLog(@"New position %f, %f", self.lastLocation.coordinate.latitude, self.lastLocation.coordinate.longitude);

    // Do something with the location or retrieve the location later
    //       :
}

停止监视

别忘了停止监视以节省电池。您可以在CLLocationManager的单个实例上启动和停止多次。

- (void)dealloc {
    [self.locationManager stopUpdatingLocation];
}

自动重新启动应用程序的注意事项

当您的应用在后台运行时,它可以(实际上经常会在一段时间后)被iOS终止。根据您使用的位置更新的类型,iOS会或不会自动为您重新启动您的应用程序。如果iOS不重新启动,则用户必须再次启动您的应用才能继续后台处理。

有关this page的更多信息。

enter image description here

阅读更多

CLLocationManager - Core Location | Apple Documentation
Handling Location Events in the Background | Apple Documentation