首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >应用程序在后台向服务器发送纬度和经度

应用程序在后台向服务器发送纬度和经度
EN

Stack Overflow用户
提问于 2016-05-12 14:02:05
回答 3查看 7.9K关注 0票数 3

我已经经历了这么多的链接,即使在那之后,我还没有找到一个正确的解决方案,以获得纬度和经度。

周期性iOS背景位置更新

具有“位置”后台模式的iOS长时间运行的后台计时器

我尝试从一些链接和论坛,但它只工作3分钟,然后应用程序是完全没有更新用户的位置。

代码语言:javascript
复制
- (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.


//create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];

//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    [locationManager startUpdatingLocation];

    NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(startTrackingBg) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
});

}
 -(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
//  store data
CLLocation *newLocation = [locations lastObject];


//tell the centralManager that you want to deferred this updatedLocation
if (_isBackgroundMode && !_deferringUpdates)
{
    _deferringUpdates = YES;
    [locationManager allowDeferredLocationUpdatesUntilTraveled:CLLocationDistanceMax timeout:10];
}
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-05-16 07:34:22

好的。

经过3天的挣扎,它是为我工作的发送纬度和经度时,应用程序是在后台,甚至在3分钟后。

我查看了我的应用程序,在后台连续发送了一个多小时的lat。

至少可以帮到一个人。

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

代码语言:javascript
复制
 1.NSLocationAlwaysUsageDescription
 2.NSLocationWhenInUseUsageDescription

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

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

然后导入重新定位框架,并将其添加到下面的代码中。

locationManager是一个全局变量。

代码语言:javascript
复制
- (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);
 }
票数 12
EN

Stack Overflow用户

发布于 2018-10-25 14:51:06

您需要参考这个苹果文档在后台处理位置事件

您需要启用位置更新、 in 、后台模式、 in 功能、Xcode项目的

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

使用此代码

代码语言:javascript
复制
locationManager.delegate = self
locationManager.startMonitoringSignificantLocationChanges()

启用重大更改位置服务。

票数 1
EN

Stack Overflow用户

发布于 2019-08-27 13:57:26

基于桑托斯的回答,其中有大多数重要步骤,使背景定位工作,我已经澄清和纠正了一些细节。

项目设置

应该将这些键添加到Xcode目标信息属性列表中。请确保向每个应用程序添加一个有效的描述,否则应用程序可能无法获得批准。

  • NSLocationAlwaysUsageDescription
  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysAndWhenInUseUsageDescription

接下来,在目标Capabilities,中,打开背景模式并检查位置更新背景提取。位置更新将启用背景中的位置,而后台获取将允许您在后台使用网络。

开始监测

首先创建一个CLLocationManager实例,配置它,然后打开后台更新,然后启动它。尽管下面的代码使用最常见的函数startUpdatingLocation来获取位置,但还有其他几个服务可供使用。选择最合适的服务是的重要,因为这对电池的使用以及应用程序是否会由iOS重新启动都有很大的影响。有关这方面的更多信息,请参见下面。

代码语言:javascript
复制
// 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的单个实例上启动和停止几次。

代码语言:javascript
复制
- (void)dealloc {
    [self.locationManager stopUpdatingLocation];
}

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

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

阅读有关此页的更多信息。

阅读更多

CLLocationManager -核心位置-苹果文档

处理后台Apple文档中的位置事件

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37189277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档