WLLocationManager.m 13.6 KB
/*
 Copyright 2010-2016 Warply Inc. All rights reserved.
 
 Redistribution and use in source and binary forms, without modification,
 are permitted provided that the following conditions are met:
 
 1. Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 
 2. Redistributions in binaryform must reproduce the above copyright notice,
 this list of conditions and the following disclaimer in the documentation
 and/or other materials provided with the distribution.
 
 THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "WLLocationManager.h"
#import "WLGlobals.h"
#import "WLEvent.h"
#import "Warply.h"
#include <math.h>

#define kGeofencingRadious 300
#define WLDefaultDistanceFilter 200

@interface WLLocationManager()
{
    BOOL even;
    double speed;
}
@end

@implementation WLLocationManager

@synthesize locationManager = _locationManager;

#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////
- (id)init
{
    self = [super init];
    if (self) {
        // By default we assume that the app will not go to the foreground and initialize the location manager with background values. If it becomes active we will reset those values in the applicationDidBecomeActive method
        
        // initialize locationManager
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [self.locationManager requestAlwaysAuthorization];
        }
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([defaults objectForKey:WL_IOS_LOCATION_FOREGROUND_MODE] != nil) {
            // if the setting has already been set in the past, use this value
            _foregroundMode = (int)[defaults integerForKey:WL_IOS_LOCATION_FOREGROUND_MODE];
        }
        else {
            //otherwise use the default value
            _foregroundMode = WLLocationModeOff;
        }
        
        if ([defaults objectForKey:WL_IOS_LOCATION_BACKGROUND_MODE] != nil) {
            // if the setting has already been set in the past, use this value
            _backgroundMode = (int)[defaults integerForKey:WL_IOS_LOCATION_BACKGROUND_MODE];
        }
        else {
            //otherwise use the default value
            _backgroundMode = WLLocationModeOff;
        }
        
        if ([defaults objectForKey:WL_IOS_GEOFENCING_ENABLED] != nil) {
            // if the setting has already been set in the past, use this value
            _geofencingEnabled = [defaults boolForKey:WL_IOS_GEOFENCING_ENABLED];
        }
        else {
            //otherwise use the default value
            _geofencingEnabled = NO;
        }
        
        
        if ([defaults objectForKey:WL_IOS_FOREGROUND_DISTANCE_FILTER] != nil) {
            // if the setting has already been set in the past, use this value
            _locationManager.distanceFilter = [defaults doubleForKey:WL_IOS_BACKGROUND_DISTANCE_FILTER];
        }
        else {
            //otherwise use the default value
            _locationManager.distanceFilter = WLDefaultDistanceFilter;
        }
        
        if ([defaults objectForKey:WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY] != nil) {
            // if the setting has already been set in the past, use this value
            _locationManager.desiredAccuracy = [defaults doubleForKey:WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY];
        }
        
        switch (self.backgroundMode) {
            case WLLocationModeSignificant:
                [_locationManager startMonitoringSignificantLocationChanges];
                break;
            case WLLocationModeStandard:
                [_locationManager startUpdatingLocation];
                break;
            default:
                break;
        }
    }
    return self;
}

#pragma mark - Properties
///////////////////////////////////////////////////////////////////////////////
- (NSString*)purpose
{
    if ([_locationManager respondsToSelector:@selector(purpose)]) {
        return [_locationManager performSelector:@selector(purpose)];
    }
    return nil;
}

///////////////////////////////////////////////////////////////////////////////
- (void)setPurpose:(NSString *)purpose
{
    if ((purpose != (NSString *)[NSNull null]) && (purpose.length > 0))
        [_locationManager performSelector:@selector(setPurpose:) withObject:purpose];
}

#pragma mark - Application Lifecycle
///////////////////////////////////////////////////////////////////////////////
- (void)applicationDidBecomeActive
{
    // When initializing we use WL_IOS_BACKGROUND_DISTANCE_FILTER and if the app becomes active we reset distanceFilter to WL_IOS_FOREGROUND_DISTANCE_FILTER
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    _locationManager.distanceFilter = [defaults doubleForKey:WL_IOS_FOREGROUND_DISTANCE_FILTER];
    _locationManager.desiredAccuracy = [defaults doubleForKey:WL_IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY];
    
    switch (_foregroundMode) {
        case WLLocationModeOff:
            [_locationManager stopUpdatingLocation];
            [_locationManager stopMonitoringSignificantLocationChanges];
            break;
        case WLLocationModeSignificant:
            [_locationManager startMonitoringSignificantLocationChanges];
            [_locationManager stopUpdatingLocation];
            break;
        case WLLocationModeStandard:
            [_locationManager startUpdatingLocation];
            [_locationManager stopMonitoringSignificantLocationChanges];
            [self removeGeofences];
    }
    
    if (self.geofencingEnabled) {
        [self sendLocation:_locationManager.location];
    }
    else [self removeGeofences];
}

///////////////////////////////////////////////////////////////////////////////
- (void)applicationDidEnterBackground
{
    if (self.geofencingEnabled) {
        [self sendLocation:_locationManager.location];
    }
    else {
        [self removeGeofences];
    }
    
    switch (_backgroundMode) {
        case WLLocationModeOff:
            [_locationManager stopUpdatingLocation];
            [_locationManager stopMonitoringSignificantLocationChanges];
            break;
        case WLLocationModeSignificant:
            [_locationManager startMonitoringSignificantLocationChanges];
            [_locationManager stopUpdatingLocation];
            break;
        case WLLocationModeStandard:
            [_locationManager startUpdatingLocation];
            _locationManager.distanceFilter = [[NSUserDefaults standardUserDefaults] doubleForKey:@"IOS_BACKGROUND_DISTANCE_FILTER"];
            [_locationManager stopMonitoringSignificantLocationChanges];
            [self removeGeofences];
    }
}

#pragma mark - Private Methods
///////////////////////////////////////////////////////////////////////////////
- (void)sendLocation:(CLLocation *)location
{
    if (location == nil) {
        return;
    }
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:GEOFENCING_POIS_ENABLED] != nil) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:GEOFENCING_POIS_ENABLED]) {
            if (![[Warply sharedService] checkIfUserLoactionIsInPois:location])
                return;
        }
    }
    
    NSDictionary *geofencing = [NSDictionary dictionaryWithObjectsAndKeys:@"tracking", @"action",
                                [NSNumber numberWithDouble:location.coordinate.latitude], @"lat",
                                [NSNumber numberWithDouble:location.coordinate.longitude], @"lon",
                                nil];
    NSDictionary *context = [NSDictionary dictionaryWithObject:geofencing forKey:@"geofencing"];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:context options:0 error:NULL];

    [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *context) {
        NSArray *regionsDicts = [context valueForKey:@"MAPP_GEOFENCING"];
        
        if (![self canUseLocation] || regionsDicts.count == 0 || _geofencingEnabled == NO)
            return;
        
        NSMutableArray *regions = [NSMutableArray array];
        [self removeGeofences];
        for (NSDictionary *regionDict in regionsDicts) {
            CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:CLLocationCoordinate2DMake([[regionDict valueForKey:@"lat"] doubleValue], [[regionDict valueForKey:@"lon"] doubleValue])
                                                                         radius:fmin(_locationManager.maximumRegionMonitoringDistance, [[regionDict valueForKey:@"radius"] doubleValue])
                                                                     identifier:[regionDict valueForKey:@"name"]];
            
            [_locationManager startMonitoringForRegion:region];
            [regions addObject:region];
        }
    } failureBlock:nil];
}

#pragma mark - CLLocationManagerDelegate
///////////////////////////////////////////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusAuthorizedAlways:
            break;
        case kCLAuthorizationStatusNotDetermined:
            break;
        case kCLAuthorizationStatusDenied:
            break;
        case kCLAuthorizationStatusRestricted:
            break;
        default:
            break;
    }
}

///////////////////////////////////////////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error { }

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    if (CLLocationCoordinate2DIsValid(newLocation.coordinate) == NO)
        return;
    
    // test the age of the location measurement to determine if the measurement is cached
    // in most cases you will not want to rely on cached measurements
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 5.0) return;
    
    speed = newLocation.speed;
    if (self.locationManagerDelegate != nil && [self.locationManagerDelegate respondsToSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)]) {
        NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)];
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sgn];
        [invocation setTarget:self.locationManagerDelegate];
        [invocation setSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)];
        [invocation setArgument:&manager atIndex:2];
        [invocation setArgument:&newLocation atIndex:3];
        [invocation setArgument:&oldLocation atIndex:4];
        [invocation invoke];
    }
    
    [self sendLocation:newLocation];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate *lastFeaturesUpdate = [defaults objectForKey:@"lastFeaturesUpdateTimestamp"];
    if ([[NSDate date] timeIntervalSinceDate:lastFeaturesUpdate] > [[defaults valueForKey:@"FEATURES_CHECK_INTERVAL"] intValue]) {
        [[Warply sharedService] getAppSettingsWithSuccessBlock:nil failureBlock:nil];
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
    [self.locationManagerDelegate locationManager:manager didEnterRegion:region];
     [self sendLocation:[[CLLocation alloc] initWithLatitude:((CLCircularRegion *)region).center.latitude longitude:((CLCircularRegion *)region).center.longitude]];
}

- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
{
    WLLOG(@"geofencing error: %@", error.localizedDescription);
}

- (void)removeGeofences
{
    for (CLRegion *region in _locationManager.monitoredRegions) {
        [_locationManager stopMonitoringForRegion:region];
    }
}

- (BOOL) canUseLocation{
    
    CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
    
    if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        if ([CLLocationManager locationServicesEnabled] &&
            ((authStatus == kCLAuthorizationStatusAuthorizedAlways) ||
             (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) ||
             ((authStatus == kCLAuthorizationStatusNotDetermined))))
            return YES;
        
        return NO;
    }
    
    if ([CLLocationManager locationServicesEnabled] && [self canUseLocation])
        return YES;
    
    return NO;
    
}

#pragma mark - Memory Management
///////////////////////////////////////////////////////////////////////////////
- (void)dealloc
{
    _locationManager.delegate = nil;
}

@end