I have strange problem with updating user's location. Sometimes my app updates location but from time to time breaks updating. I do not know where is problem, my code (from AppDelegate.m) is below:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"Went to Background");
// Only monitor significant changes
[locationManager startMonitoringSignificantLocationChanges];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Start location services
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// Only report to location manager if the user has traveled 1000 meters
locationManager.distanceFilter = 1000.0f;
locationManager.delegate = self;
locationManager.activityType = CLActivityTypeAutomotiveNavigation;
[locationManager stopMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// Check if running in background or not
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
isInBackground = YES;
}
if (isInBackground) {
// If we're running in the background, run sendBackgroundLocationToServer
[self sendBackgroundLocationToServer:[locations lastObject]];
} else {
// If we're not in the background wait till the GPS is accurate to send it to the server
if ([[locations lastObject] horizontalAccuracy] < 100.0f) {
[self sendDataToServer:[locations lastObject]];
}
}
}
-(void) sendBackgroundLocationToServer:(CLLocation *)location
{
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
// Send the data
[self sendDataToServer:location];
if (bgTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
-(void) sendDataToServer:(CLLocation *)newLocation
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *lat = [NSString stringWithFormat:@"%.8f", newLocation.coordinate.latitude];
NSString *lng = [NSString stringWithFormat:@"%.8f", newLocation.coordinate.longitude];
[APIConnection SaveMyPositionWitLat:lat withLng:lng];
});
}
I need to update location every hour or if user change location more then 1000m. I chose the second way in order to save battery but my solution do not work as I need.
I would greatly appreciate any help on this, Thanks in advance!