WLLocationManager.m
13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
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