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

标签 ios background nstimer core-location

我浏览了很多链接,甚至在那之后我还没有找到一个合适的解决方案来获取经纬度。

Periodic iOS background location updates

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

我尝试了一些链接和论坛,但它只工作了 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 分钟后,当应用程序处于后台时,它也可以为我发送纬度和经度。

我检查了我的应用程序,在后台持续发送经纬度超过一个小时。

它至少可以帮助一些人。

首先请在您的 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);
 }

关于ios - 应用程序在后台时向服务器发送纬度和经度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37189277/

相关文章:

html - 幻灯片/旋转木马和背景 img

background - Unity 中的 Kinect 游戏 : How to do background removal

ios - 读取 NSTimer 子类的 public var valid 失败,错误为 'isValid only defined for abstract class'

objective-c - NSTimer 问题

ios - 使用_框架!在 cocoapods 中进行分析

ios - HTTPS 服务不工作

jquery - 在全日历中显示图像作为背景

ios - 如何通过 UICollectionViewController (Swift) 中的 didSelectItemAtIndexPath() 方法访问所有单元格

iphone - 从服务器下载图像并仅覆盖修改后的图像

ios - NSTimer在同一线程上两次调用选择器方法?