Sending Latitude and Longitude to Server when app is in background
Asked Answered
E

3

3

I have gone through so many links, even after that I haven't found a proper solution for getting latitude and longitude.

Periodic iOS background location updates

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

I tried from some links and forums but it is working for only 3 mins, then app is not at all updating the user location.

- (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];
}
}
Effable answered 12/5, 2016 at 14:2 Comment(0)
E
12

Ok.

After struggling for 3days, it is working for me for sending latitude and longitude when app is in background even after 3 mins.

I checked my app, continuously sending lat long for more than a hour in background.

It can help some one at least.

First Please add below two keys in your pList.

 1.NSLocationAlwaysUsageDescription
 2.NSLocationWhenInUseUsageDescription

Bothe are strings and you can give any value.

Then please turn on background fetch and check location updates under capabilities in project section.

Then import Corelocation framework and add this below code.

locationManager is a global variable.

- (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);
 }
Effable answered 16/5, 2016 at 7:34 Comment(9)
@Santo...Please check this bro..and tried to help me.. #37338966Baal
@SurajSukale first let me know, are you getting current location when you build?Effable
no bro...Actually i'm very new in this app development (1st time working on this specific domain-location ).... can you help me to solve thisBaal
follow this links #12736586 appcoda.com/how-to-get-current-location-iphone-userEffable
Let us continue this discussion in chat.Effable
Guys were you able to solve it if yes please ping me at [email protected]Bechtel
Great Answer. I appreciate it.Tye
@Effable can you send me your location manager class written in OBJ-C ? Here is my email address - [email protected]Uralaltaic
@Effable in the background don't you think NSTimer will be suspended ?Uralaltaic
G
1

You need to refer this apple documentation handling location events in the background

You need to enable location updates in background modes in capabilities of your Xcode project.

The Standard location service wont work in background mode so you have to use either Significant-change location service or Visits service .

Use this code to

locationManager.delegate = self
locationManager.startMonitoringSignificantLocationChanges()

enable Significant-change location service.

Gogh answered 25/10, 2018 at 14:51 Comment(0)
S
0

Building on Santos answer which has most of the important steps to make background positioning work, I have clarified and corrected some details.

Project settings

You should add these keys to your Xcode Target Info property list. Make sure to add a valid description to each of them, or your app might fail approval.

  • NSLocationAlwaysUsageDescription
  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysAndWhenInUseUsageDescription

enter image description here

Next, in Target Capabilities, Turn on Background Modes and check Location updates and Background fetch. Location updates will enable locations in the background and background fetch will allow you to use the network in the background. enter image description here

Start monitoring

Start by creating an instance of CLLocationManager, configure it and turn on background updates, then start it. Although the code below uses the most common function startUpdatingLocation to get locations, there are several other services to use. It is important to choose the most suitable service as this impacts greatly on battery usage and if the app will be re-launched or not by iOS. See below for more info on this.

// 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
    //       :
}

Stop monitoring

Don't forget to stop monitoring to conserve battery. You can start and stop several times on a single instance of CLLocationManager.

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

Automatic app re-launch considerations

When your app is running in the background it can (and actually frequently will after some time) be terminated by iOS. Depending on the type of location updates you are using, iOS will or will not re-launch your app automatically for you. In cases where iOS do not re-launch, the user must start your app again to continue background processing.

Read more on this page.

enter image description here

Read more

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

Seaway answered 27/8, 2019 at 13:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.