1
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
    self.locationManager   = [[CLLocationManager alloc] init];
    self.locationManager.delegate  = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.activityType = CLActivityTypeFitness;
    // Movement threshold for new events.
    self.locationManager.distanceFilter = 20;

    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        //  [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager requestAlwaysAuthorization];
    }

    [self.locationManager startUpdatingLocation];
    [self.locationManager startMonitoringSignificantLocationChanges];

}

return YES;

}
- (void)applicationDidEnterBackground:(UIApplication *)application {
_isBackGround=YES;

[self.locationManager stopMonitoringSignificantLocationChanges];
  [self.locationManager requestAlwaysAuthorization];
 [self.locationManager startMonitoringSignificantLocationChanges];

}
    - (void)applicationDidBecomeActive:(UIApplication *)application {
_isBackGround=NO;    
[self.locationManager stopMonitoringSignificantLocationChanges];
self.locationManager   = [[CLLocationManager alloc] init];
self.locationManager.delegate  = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.activityType = CLActivityTypeFitness;
// Movement threshold for new events.
self.locationManager.distanceFilter = 20;

if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
    //  [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestAlwaysAuthorization];
}

[self.locationManager startUpdatingLocation];
[self.locationManager startMonitoringSignificantLocationChanges];
}

   -(void) sendBackgroundLocationToServer
{
    if([[AppHelper nullCheck:[AppHelper userDefaultsForKey:USER_ID]]     length]>0){
   NSString * query = [NSString stringWithFormat:@"localUpdate=='YES'"];
   NSArray* arrData=[self searchObjectsForEntity:@"UserLocation" withPredicate:[NSPredicate predicateWithFormat:query] andSortKey:nil andSortAscending:NO];
  if(arrData.count){
            [self sendUpdateUserLocation:arrData];
     }
}

}
 - (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSDate *eventDate = newLocation.timestamp;

NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
CLLocationDistance dist=[newLocation distanceFromLocation:oldLocation];
NSLog(@"%f",dist);

if ([[AppHelper nullCheck:[AppHelper userDefaultsForKey:K_LATITUDE]] length] <3) {
    [AppHelper saveToUserDefaults:[NSString stringWithFormat:@"%f",newLocation.coordinate.latitude] withKey:K_LATITUDE];
    [AppHelper saveToUserDefaults:[NSString stringWithFormat:@"%f",newLocation.coordinate.longitude] withKey:K_LONGITUDE];
     [[Service sharedEventController]parseUserLocationeList:[NSString stringWithFormat:@"%f",newLocation.coordinate.latitude] andLong:[NSString stringWithFormat:@"%f",newLocation.coordinate.longitude]];
}

BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
    isInBackground = YES;
}


    [AppHelper saveToUserDefaults:[NSString stringWithFormat:@"%f",newLocation.coordinate.latitude] withKey:K_LATITUDE];
    [AppHelper saveToUserDefaults:[NSString stringWithFormat:@"%f",newLocation.coordinate.longitude] withKey:K_LONGITUDE];

    [[Service sharedEventController]parseUserLocationeList:[NSString stringWithFormat:@"%f",newLocation.coordinate.latitude] andLong:[NSString stringWithFormat:@"%f",newLocation.coordinate.longitude]];
    [self sendBackgroundLocationToServer];

}






-(void)sendUpdateUserLocation:(NSArray*)ArrData{

if([AppHelper appDelegate].checkNetworkReachability)
{

self.bgTask = [[UIApplication sharedApplication]
          beginBackgroundTaskWithExpirationHandler:^{
               [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
               }];

NSMutableArray *arr=[NSMutableArray new];
    for(UserLocation *loc in ArrData){
        NSMutableDictionary *parameters= [NSMutableDictionary new];
        parameters[@"lat"]=loc.lat;
        parameters[@"long"]=loc.longT;
        [arr addObject:parameters];
    }
NSMutableDictionary *parameters =[NSMutableDictionary new];
parameters[@"uid"]=[AppHelper userDefaultsForKey:USER_ID];
 parameters[@"data"]=arr;

NSString *baseURL = [NSString stringWithFormat:@"%@%@",BaseUrl,UPDATE_LOCATION];
    if (self.bgTask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }

   AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager POST:baseURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    [[AppHelper sharedInstance]hideIndicator];
    for (NSManagedObject *manObj in ArrData) {
        [self.managedObjectContext deleteObject:manObj];
        // NSLog(@"delete objects for predicate %@", predicate);
    }
     [self saveContext];
      NSLog(@"JSON: %@", responseObject);
    if (self.bgTask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
         self.bgTask = UIBackgroundTaskInvalid;
    }

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    [[AppHelper sharedInstance]hideIndicator];
    if (self.bgTask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }
}];

}
 }

I am using this code to send location to server after 20 meter change in background.I have checked when app is open then it's work good. But in background it works around 5 min.And after that it doesn't work.

I have tried more but I have not found any solution.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • You requested for using Location Service Always, but have you provided the reason of using it in `.plist` ? – Raptor Feb 12 '16 at 07:29
  • yes location services is always and I have added in .plist NSLocationAlwaysUsageDescription NSLocationWhenInUseUsageDescription and Also I have checked in background modes Capabilities Location Updates Background Fetch Remote notification – Kunal Kumar Feb 12 '16 at 07:34
  • And also I had view one thing data is being on local database.Only data is not being send on server after 5 min. Please give any idea ASAP – Kunal Kumar Feb 12 '16 at 08:04
  • Read also: http://stackoverflow.com/questions/19042894/periodic-ios-background-location-updates – Raptor Feb 12 '16 at 08:10
  • I had checked that but it didn't worked. – Kunal Kumar Feb 12 '16 at 12:14

0 Answers0