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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
|
#import "MWMLocationManager.h"
#import <Pushwoosh/PushNotificationManager.h>
#import "MWMAlertViewController.h"
#import "MWMCommon.h"
#import "MWMController.h"
#import "MWMLocationObserver.h"
#import "MWMLocationPredictor.h"
#import "MWMRouter.h"
#import "MapsAppDelegate.h"
#import "Statistics.h"
#import "3party/Alohalytics/src/alohalytics_objc.h"
#include "Framework.h"
#include "map/gps_tracker.hpp"
#include "std/map.hpp"
namespace
{
using Observer = id<MWMLocationObserver>;
using Observers = NSHashTable<Observer>;
location::GpsInfo gpsInfoFromLocation(CLLocation * l, location::TLocationSource source)
{
location::GpsInfo info;
info.m_source = source;
info.m_latitude = l.coordinate.latitude;
info.m_longitude = l.coordinate.longitude;
info.m_timestamp = l.timestamp.timeIntervalSince1970;
if (l.horizontalAccuracy >= 0.0)
info.m_horizontalAccuracy = l.horizontalAccuracy;
if (l.verticalAccuracy >= 0.0)
{
info.m_verticalAccuracy = l.verticalAccuracy;
info.m_altitude = l.altitude;
}
if (l.course >= 0.0)
info.m_bearing = l.course;
if (l.speed >= 0.0)
info.m_speed = l.speed;
return info;
}
location::CompassInfo compassInfoFromHeading(CLHeading * h)
{
location::CompassInfo info;
if (h.trueHeading >= 0.0)
info.m_bearing = my::DegToRad(h.trueHeading);
else if (h.headingAccuracy >= 0.0)
info.m_bearing = my::DegToRad(h.magneticHeading);
return info;
}
typedef NS_OPTIONS(NSUInteger, MWMLocationFrameworkUpdate) {
MWMLocationFrameworkUpdateNone = 0,
MWMLocationFrameworkUpdateLocation = 1 << 0,
MWMLocationFrameworkUpdateHeading = 1 << 1,
MWMLocationFrameworkUpdateStatus = 1 << 2
};
enum class GeoMode
{
Pending,
InPosition,
NotInPosition,
FollowAndRotate,
VehicleRouting,
PedestrianRouting,
BicycleRouting
};
struct DesiredAccuracy
{
CLLocationAccuracy charging;
CLLocationAccuracy battery;
};
struct GeoModeSettings
{
CLLocationDistance distanceFilter;
DesiredAccuracy accuracy;
};
map<GeoMode, GeoModeSettings> const kGeoSettings{
{GeoMode::Pending,
{.distanceFilter = kCLDistanceFilterNone,
.accuracy = {.charging = kCLLocationAccuracyBestForNavigation,
.battery = kCLLocationAccuracyBestForNavigation}}},
{GeoMode::InPosition,
{.distanceFilter = 2,
.accuracy = {.charging = kCLLocationAccuracyBestForNavigation,
.battery = kCLLocationAccuracyBest}}},
{GeoMode::NotInPosition,
{.distanceFilter = 5,
.accuracy = {.charging = kCLLocationAccuracyBestForNavigation,
.battery = kCLLocationAccuracyBest}}},
{GeoMode::FollowAndRotate,
{.distanceFilter = 2,
.accuracy = {.charging = kCLLocationAccuracyBestForNavigation,
.battery = kCLLocationAccuracyBest}}},
{GeoMode::VehicleRouting,
{.distanceFilter = kCLDistanceFilterNone,
.accuracy = {.charging = kCLLocationAccuracyBestForNavigation,
.battery = kCLLocationAccuracyBest}}},
{GeoMode::PedestrianRouting,
{.distanceFilter = 2,
.accuracy = {.charging = kCLLocationAccuracyBestForNavigation,
.battery = kCLLocationAccuracyBest}}},
{GeoMode::BicycleRouting,
{.distanceFilter = 2,
.accuracy = {.charging = kCLLocationAccuracyBestForNavigation,
.battery = kCLLocationAccuracyBest}}}};
BOOL keepRunningInBackground()
{
bool const needGPSForTrackRecorder = GpsTracker::Instance().IsEnabled();
if (needGPSForTrackRecorder)
return YES;
auto const isRouteBuilt = [MWMRouter isRouteBuilt];
auto const isRouteFinished = [MWMRouter isRouteFinished];
auto const isRouteRebuildingOnly = [MWMRouter isRouteRebuildingOnly];
auto const needGPSForRouting = ((isRouteBuilt || isRouteRebuildingOnly) && !isRouteFinished);
if (needGPSForRouting)
return YES;
return NO;
}
NSString * const kLocationPermissionRequestedKey = @"kLocationPermissionRequestedKey";
BOOL isPermissionRequested()
{
return [[NSUserDefaults standardUserDefaults] boolForKey:kLocationPermissionRequestedKey];
}
void setPermissionRequested()
{
NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
[ud setBool:YES forKey:kLocationPermissionRequestedKey];
[ud synchronize];
}
} // namespace
@interface MWMLocationManager ()<CLLocationManagerDelegate>
@property(nonatomic) BOOL started;
@property(nonatomic) CLLocationManager * locationManager;
@property(nonatomic) GeoMode geoMode;
@property(nonatomic) CLHeading * lastHeadingInfo;
@property(nonatomic) CLLocation * lastLocationInfo;
@property(nonatomic) location::TLocationError lastLocationStatus;
@property(nonatomic) MWMLocationPredictor * predictor;
@property(nonatomic) Observers * observers;
@property(nonatomic) MWMLocationFrameworkUpdate frameworkUpdateMode;
@property(nonatomic) location::TLocationSource locationSource;
@end
@implementation MWMLocationManager
#pragma mark - Init
+ (MWMLocationManager *)manager
{
static MWMLocationManager * manager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[super alloc] initManager];
});
return manager;
}
- (instancetype)initManager
{
self = [super init];
if (self)
_observers = [Observers weakObjectsHashTable];
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
self.locationManager.delegate = nil;
}
+ (void)start { [self manager].started = YES; }
#pragma mark - Add/Remove Observers
+ (void)addObserver:(Observer)observer
{
runAsyncOnMainQueue(^{
MWMLocationManager * manager = [self manager];
[manager.observers addObject:observer];
[manager processLocationUpdate:manager.lastLocationInfo];
});
}
+ (void)removeObserver:(Observer)observer
{
runAsyncOnMainQueue(^{
[[self manager].observers removeObject:observer];
});
}
#pragma mark - App Life Cycle
+ (void)applicationDidBecomeActive
{
if (isPermissionRequested() || ![Alohalytics isFirstSession])
{
[self start];
[[self manager] updateFrameworkInfo];
}
}
+ (void)applicationWillResignActive
{
BOOL const keepRunning = isPermissionRequested() && keepRunningInBackground();
MWMLocationManager * manager = [self manager];
CLLocationManager * locationManager = manager.locationManager;
if ([locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
[locationManager setAllowsBackgroundLocationUpdates:keepRunning];
manager.started = keepRunning;
}
#pragma mark - Getters
+ (CLLocation *)lastLocation
{
MWMLocationManager * manager = [self manager];
if (!manager.started || !manager.lastLocationInfo ||
manager.lastLocationInfo.horizontalAccuracy < 0 ||
manager.lastLocationStatus != location::TLocationError::ENoError)
return nil;
return manager.lastLocationInfo;
}
+ (BOOL)isLocationProhibited
{
auto const status = [self manager].lastLocationStatus;
return status == location::TLocationError::EDenied ||
status == location::TLocationError::EGPSIsOff;
}
+ (CLHeading *)lastHeading
{
MWMLocationManager * manager = [self manager];
if (!manager.started || !manager.lastHeadingInfo || manager.lastHeadingInfo.headingAccuracy < 0)
return nil;
return manager.lastHeadingInfo;
}
#pragma mark - Observer notifications
- (void)processLocationStatus:(location::TLocationError)locationError
{
self.lastLocationStatus = locationError;
if (self.lastLocationStatus != location::TLocationError::ENoError)
self.frameworkUpdateMode |= MWMLocationFrameworkUpdateStatus;
for (Observer observer in self.observers)
{
if ([observer respondsToSelector:@selector(onLocationError:)])
[observer onLocationError:self.lastLocationStatus];
}
}
- (void)processHeadingUpdate:(CLHeading *)headingInfo
{
self.lastHeadingInfo = headingInfo;
self.frameworkUpdateMode |= MWMLocationFrameworkUpdateHeading;
location::CompassInfo const compassInfo = compassInfoFromHeading(headingInfo);
for (Observer observer in self.observers)
{
if ([observer respondsToSelector:@selector(onHeadingUpdate:)])
[observer onHeadingUpdate:compassInfo];
}
}
- (void)processLocationUpdate:(CLLocation *)locationInfo
{
if (!locationInfo || self.lastLocationStatus != location::TLocationError::ENoError)
return;
[self onLocationUpdate:locationInfo source:self.locationSource];
if (![self.lastLocationInfo isEqual:locationInfo])
[self.predictor reset:locationInfo];
}
- (void)onLocationUpdate:(CLLocation *)locationInfo source:(location::TLocationSource)source
{
location::GpsInfo const gpsInfo = gpsInfoFromLocation(locationInfo, source);
GpsTracker::Instance().OnLocationUpdated(gpsInfo);
self.lastLocationInfo = locationInfo;
self.locationSource = source;
self.frameworkUpdateMode |= MWMLocationFrameworkUpdateLocation;
for (Observer observer in self.observers)
{
if ([observer respondsToSelector:@selector(onLocationUpdate:)])
[observer onLocationUpdate:gpsInfo];
}
}
#pragma mark - Location Status
- (void)setLastLocationStatus:(location::TLocationError)lastLocationStatus
{
_lastLocationStatus = lastLocationStatus;
switch (lastLocationStatus)
{
case location::ENoError: break;
case location::ENotSupported:
[[MWMAlertViewController activeAlertController] presentLocationServiceNotSupportedAlert];
break;
case location::EDenied:
[[MWMAlertViewController activeAlertController] presentLocationAlert];
break;
case location::EGPSIsOff:
// iOS shows its own alert.
break;
}
}
#pragma mark - My Position
+ (void)setMyPositionMode:(MWMMyPositionMode)mode
{
MWMLocationManager * manager = [self manager];
[manager.predictor setMyPositionMode:mode];
[manager processLocationStatus:manager.lastLocationStatus];
if ([MWMRouter isRoutingActive])
{
switch ([MWMRouter type])
{
case MWMRouterTypeVehicle: manager.geoMode = GeoMode::VehicleRouting; break;
case MWMRouterTypePedestrian: manager.geoMode = GeoMode::PedestrianRouting; break;
case MWMRouterTypeBicycle: manager.geoMode = GeoMode::BicycleRouting; break;
case MWMRouterTypeTaxi: break;
}
}
else
{
switch (mode)
{
case MWMMyPositionModePendingPosition: manager.geoMode = GeoMode::Pending; break;
case MWMMyPositionModeNotFollowNoPosition:
case MWMMyPositionModeNotFollow: manager.geoMode = GeoMode::NotInPosition; break;
case MWMMyPositionModeFollow: manager.geoMode = GeoMode::InPosition; break;
case MWMMyPositionModeFollowAndRotate: manager.geoMode = GeoMode::FollowAndRotate; break;
}
}
}
#pragma mark - Prediction
- (MWMLocationPredictor *)predictor
{
if (!_predictor)
{
__weak MWMLocationManager * weakSelf = self;
_predictor = [[MWMLocationPredictor alloc] initWithOnPredictionBlock:^(CLLocation * location) {
[weakSelf onLocationUpdate:location source:location::EPredictor];
}];
}
return _predictor;
}
#pragma mark - Device notifications
- (void)orientationChanged
{
self.locationManager.headingOrientation =
(CLDeviceOrientation)[UIDevice currentDevice].orientation;
}
- (void)batteryStateChangedNotification:(NSNotification *)notification
{
[self refreshGeoModeSettings];
}
#pragma mark - Location manager
- (void)setGeoMode:(GeoMode)geoMode
{
if (_geoMode == geoMode)
return;
_geoMode = geoMode;
CLLocationManager * locationManager = self.locationManager;
switch (geoMode)
{
case GeoMode::Pending:
case GeoMode::InPosition:
case GeoMode::NotInPosition:
case GeoMode::FollowAndRotate: locationManager.activityType = CLActivityTypeOther; break;
case GeoMode::VehicleRouting:
locationManager.activityType = CLActivityTypeAutomotiveNavigation;
break;
case GeoMode::PedestrianRouting:
case GeoMode::BicycleRouting: locationManager.activityType = CLActivityTypeFitness; break;
}
[self refreshGeoModeSettings];
}
- (void)refreshGeoModeSettings
{
UIDeviceBatteryState const state = [UIDevice currentDevice].batteryState;
BOOL const isCharging =
(state == UIDeviceBatteryStateCharging || state == UIDeviceBatteryStateFull);
GeoModeSettings const settings = kGeoSettings.at(self.geoMode);
CLLocationManager * locationManager = self.locationManager;
locationManager.desiredAccuracy =
isCharging ? settings.accuracy.charging : settings.accuracy.battery;
locationManager.distanceFilter = settings.distanceFilter;
}
- (CLLocationManager *)locationManager
{
if (!_locationManager)
{
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
[self refreshGeoModeSettings];
_locationManager.pausesLocationUpdatesAutomatically = YES;
_locationManager.headingFilter = 3.0;
}
return _locationManager;
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)heading
{
[self processHeadingUpdate:heading];
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation * location = locations.lastObject;
// According to documentation, lat and lon are valid only if horizontalAccuracy is non-negative.
// So we filter out such events completely.
if (location.horizontalAccuracy < 0.)
return;
self.lastLocationStatus = location::TLocationError::ENoError;
self.locationSource = location::EAppleNative;
[self processLocationUpdate:location];
[[Statistics instance] logLocation:location];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
if (self.lastLocationStatus == location::TLocationError::ENoError && error.code == kCLErrorDenied)
[self processLocationStatus:location::EDenied];
}
#pragma mark - Start / Stop
- (void)setStarted:(BOOL)started
{
if (_started == started)
return;
NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
if (started)
{
_started = [self start];
[notificationCenter addObserver:self
selector:@selector(orientationChanged)
name:UIDeviceOrientationDidChangeNotification
object:nil];
[notificationCenter addObserver:self
selector:@selector(batteryStateChangedNotification:)
name:UIDeviceBatteryStateDidChangeNotification
object:nil];
}
else
{
_started = NO;
[self stop];
[notificationCenter removeObserver:self
name:UIDeviceOrientationDidChangeNotification
object:nil];
[notificationCenter removeObserver:self
name:UIDeviceBatteryStateDidChangeNotification
object:nil];
}
}
- (BOOL)start
{
auto const doStart = ^{
LOG(LINFO, ("startUpdatingLocation"));
CLLocationManager * locationManager = self.locationManager;
if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];
setPermissionRequested();
if ([CLLocationManager headingAvailable])
[locationManager startUpdatingHeading];
[[PushNotificationManager pushManager] startLocationTracking];
};
if ([CLLocationManager locationServicesEnabled])
{
switch ([CLLocationManager authorizationStatus])
{
case kCLAuthorizationStatusAuthorizedWhenInUse:
case kCLAuthorizationStatusAuthorizedAlways:
case kCLAuthorizationStatusNotDetermined: doStart(); return YES;
case kCLAuthorizationStatusRestricted:
case kCLAuthorizationStatusDenied: [self processLocationStatus:location::EDenied]; break;
}
}
else
{
// Call start to make iOS show its alert to request geo service.
doStart();
[self processLocationStatus:location::EGPSIsOff];
}
return NO;
}
- (void)stop
{
LOG(LINFO, ("stopUpdatingLocation"));
CLLocationManager * locationManager = self.locationManager;
[locationManager stopUpdatingLocation];
if ([CLLocationManager headingAvailable])
[locationManager stopUpdatingHeading];
[[PushNotificationManager pushManager] stopLocationTracking];
}
#pragma mark - Framework
- (void)updateFrameworkInfo
{
auto app = UIApplication.sharedApplication;
if (app.applicationState != UIApplicationStateActive)
return;
auto delegate = static_cast<MapsAppDelegate *>(app.delegate);
if (delegate.isDrapeEngineCreated)
{
auto & f = GetFramework();
if (self.frameworkUpdateMode & MWMLocationFrameworkUpdateLocation)
{
location::GpsInfo const gpsInfo =
gpsInfoFromLocation(self.lastLocationInfo, self.locationSource);
f.OnLocationUpdate(gpsInfo);
}
if (self.frameworkUpdateMode & MWMLocationFrameworkUpdateHeading)
f.OnCompassUpdate(compassInfoFromHeading(self.lastHeadingInfo));
if (self.frameworkUpdateMode & MWMLocationFrameworkUpdateStatus)
f.OnLocationError(self.lastLocationStatus);
self.frameworkUpdateMode = MWMLocationFrameworkUpdateNone;
}
else
{
runAsyncOnMainQueue(^{
[self updateFrameworkInfo];
});
}
}
#pragma mark - Property
- (void)setFrameworkUpdateMode:(MWMLocationFrameworkUpdate)frameworkUpdateMode
{
if (frameworkUpdateMode != _frameworkUpdateMode &&
_frameworkUpdateMode == MWMLocationFrameworkUpdateNone &&
frameworkUpdateMode != MWMLocationFrameworkUpdateNone)
{
_frameworkUpdateMode = frameworkUpdateMode;
[self updateFrameworkInfo];
}
else
{
_frameworkUpdateMode = frameworkUpdateMode;
}
}
@end
|