Ios 应用程序处于后台时向服务器发送纬度和经度

Ios 应用程序处于后台时向服务器发送纬度和经度,ios,background,nstimer,core-location,Ios,Background,Nstimer,Core Location,我已经通过了这么多的链接,即使在那之后,我还没有找到一个合适的解决方案来获取纬度和经度 我尝试了一些链接和论坛,但它只工作了3分钟,然后应用程序根本没有更新用户位置 - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store eno

我已经通过了这么多的链接,即使在那之后,我还没有找到一个合适的解决方案来获取纬度和经度

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

- (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];
}
}

在苦苦挣扎了3天后,当应用程序在后台运行时,即使在3分钟后,我仍然可以发送纬度和经度

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

它至少可以帮助一些人

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

 1.NSLocationAlwaysUsageDescription
 2.NSLocationWhenInUseUsageDescription
两者都是字符串,您可以给出任何值

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

然后导入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);
 }

您需要参考此apple文档

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

标准定位服务在后台模式下无法运行,因此您必须使用重大变更定位服务或访问服务

使用此代码

locationManager.delegate = self
locationManager.startMonitoringSignificantLocationChanges()

启用重大更改定位服务。

基于Santos answer,它有使背景定位工作正常的大多数重要步骤,我已经澄清并更正了一些细节

项目设置 您应该将这些键添加到Xcode目标Info属性列表中。请确保为每个应用程序添加有效的说明,否则您的应用程序可能无法获得批准

  • NSLocationAlwaysUsageDescription
  • n不使用时的位置说明
  • n位置始终和何时使用说明

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

开始监控 首先创建
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
    //       :
}
自动应用程序重新启动注意事项 当你的应用程序在后台运行时,它可以(事实上经常会在一段时间后)被iOS终止。根据您使用的位置更新类型,iOS将或不会自动为您重新启动应用程序。如果iOS没有重新启动,用户必须再次启动应用程序才能继续后台处理

阅读更多关于

阅读更多

@Santo…请检查一下这个兄弟..并试着帮我@SurajSukale首先让我知道,你在构建时是否获得当前位置?没有兄弟…实际上我在这个应用程序开发方面非常新(第一次在这个特定的域位置上工作)。。。。你能帮我解决这个问题吗?请点击这个链接。
- (void)dealloc {
    [self.locationManager stopUpdatingLocation];
}