NotABot
NotABot

Reputation: 526

iOS app background location access using a timer

I am looking for a solution to access/stop location services while app is in the background. My app takes continuous location when it's sent to background (It has access to continuous location) . It's necessary for the app functionality.

So I would like to know few things:

Upvotes: 1

Views: 211

Answers (1)

ron27
ron27

Reputation: 181

Background location updation can be done using following code:

In Appdelegate class:

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

if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {

        // This "afterResume" flag is just to show that he receiving location updates
        // are actually from the key "UIApplicationLaunchOptionsLocationKey"
        self.shareModel.afterResume = YES;

        [self.shareModel startMonitoringLocation];
    }

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

[self.shareModel stopContinuosLocationUpdate];
    [self.shareModel restartMonitoringLocation];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {

//Remove the "afterResume" Flag after the app is active again.
    self.shareModel.afterResume = NO;

    [self.shareModel startContinuosLocationUpdate];
}

In Location update class, say LocationManager.m:

#import <CoreLocation/CoreLocation.h>

@property (nonatomic) CLLocationManager * anotherLocationManager;

- (void)startContinuosLocationUpdate
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    if (status == kCLAuthorizationStatusDenied)
    {
        NSLog(@"Location services are disabled in settings.");
    }
    else
    {
        // for iOS 8
        if ([self.anotherLocationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.anotherLocationManager requestAlwaysAuthorization];
        }
        // for iOS 9
        if ([self.anotherLocationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
        {
            [self.anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
        }

        [self.anotherLocationManager startUpdatingLocation];
    }
}

- (void)stopContinuosLocationUpdate
{
    [self.anotherLocationManager stopUpdatingLocation];
}

- (void)startMonitoringLocation
{
    if (_anotherLocationManager)
        [_anotherLocationManager stopMonitoringSignificantLocationChanges];

    self.anotherLocationManager = [[CLLocationManager alloc]init];
    _anotherLocationManager.delegate = self;
    _anotherLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    _anotherLocationManager.activityType = CLActivityTypeOtherNavigation;

    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        [_anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
    }
    else if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        [_anotherLocationManager requestAlwaysAuthorization];
    }
    [_anotherLocationManager startMonitoringSignificantLocationChanges];
}

- (void)restartMonitoringLocation
{
    [_anotherLocationManager stopMonitoringSignificantLocationChanges];

    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        [_anotherLocationManager setAllowsBackgroundLocationUpdates:YES];
    }
    else if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        [_anotherLocationManager requestAlwaysAuthorization];
    }
    [_anotherLocationManager startMonitoringSignificantLocationChanges];
}


#pragma mark - CLLocationManager Delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    if(_dictLocation && [_dictLocation isKindOfClass:[NSDictionary class]])
    {
        float latitudeValue = [[RVCommon validateDataForNumber:_dictLocation[@"lat"]] floatValue];
        float longitudeValue = [[RVCommon validateDataForNumber:_dictLocation[@"lng"]] floatValue];
        CLLocation *facilityLocation = [[CLLocation alloc] initWithLatitude:latitudeValue longitude:longitudeValue];
        CLLocation *mostRecentLocation = locations.lastObject;

        CLLocationDistance distanceInMeters = [mostRecentLocation distanceFromLocation:facilityLocation];
        if (distanceInMeters <= 500.0)
        {
            //Here I am informing the server when user is within 500mts of the coordinate. 
        }
    }

    NSLog(@"locationManager didUpdateLocations: %@",locations);
}

Upvotes: 1

Related Questions