-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathGeolocationModule.m
1199 lines (1025 loc) Β· 43.3 KB
/
GeolocationModule.m
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Titanium SDK
* Copyright TiDev, Inc. 04/07/2022-Present. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#ifdef USE_TI_GEOLOCATION
#import "GeolocationModule.h"
#import <Contacts/CNPostalAddress.h>
#import <Contacts/CNPostalAddressFormatter.h>
#import <TitaniumKit/APSHTTPClient.h>
#import <TitaniumKit/KrollPromise.h>
#import <TitaniumKit/NSData+Additions.h>
#import <TitaniumKit/TiApp.h>
#import <sys/utsname.h>
extern NSString *const TI_APPLICATION_GUID;
@interface GeolocationCallback : NSObject <APSHTTPRequestDelegate> {
JSValue *callback;
KrollPromise *promise;
}
- (id)initWithCallback:(JSValue *)callback andPromise:(KrollPromise *)promise;
@end
@implementation GeolocationCallback
- (id)initWithCallback:(JSValue *)callback_ andPromise:(KrollPromise *)promise_
{
// Ignore analyzer warning here. Delegate will call autorelease onLoad or onError.
if (self = [super init]) {
// FIXME Use JSManagedValue here?
if (![callback_ isUndefined]) { // guard against user not supplying a callback function!
callback = [callback_ retain];
}
promise = [promise_ retain];
}
return self;
}
- (void)dealloc
{
RELEASE_TO_NIL(callback);
RELEASE_TO_NIL(promise);
[super dealloc];
}
- (void)requestSuccess:(NSDictionary *)data
{
}
- (void)requestError:(NSError *)error
{
NSString *message = [TiUtils messageFromError:error];
NSDictionary *event = [TiUtils dictionaryWithCode:[error code] message:message];
if (callback != nil) {
[callback callWithArguments:@[ event ]];
}
[promise rejectWithErrorMessage:message];
}
@end
@interface HeadingCallback : GeolocationCallback
@end
@interface PositionCallback : GeolocationCallback
@end
@interface ForwardGeoCallback : GeolocationCallback
@end
@interface ReverseGeoCallback : GeolocationCallback
@end
@implementation HeadingCallback
- (void)fireEvent:(id)event withProxy:(ObjcProxy *)proxy
{
if (callback != nil) {
[proxy _fireEventToListener:@"heading" withObject:event listener:callback];
}
if ([event[@"success"] boolValue]) {
[promise resolve:@[ event ]];
} else {
[promise rejectWithErrorMessage:event[@"error"]];
}
}
@end
@implementation PositionCallback
- (void)fireEvent:(id)event withProxy:(ObjcProxy *)proxy
{
if (callback != nil) {
[proxy _fireEventToListener:@"location" withObject:event listener:callback];
}
if ([event[@"success"] boolValue]) {
[promise resolve:@[ event ]];
} else {
[promise rejectWithErrorMessage:event[@"error"]];
}
}
@end
@implementation ForwardGeoCallback
- (void)requestSuccess:(NSDictionary *)event
{
if (callback != nil) {
[callback callWithArguments:@[ event ]];
}
[promise resolve:@[ event ]];
}
@end
@implementation ReverseGeoCallback
- (void)requestSuccess:(NSDictionary *)event
{
if (callback != nil) {
[callback callWithArguments:@[ event ]];
}
[promise resolve:@[ event ]];
}
@end
@implementation GeolocationModule
@synthesize allowsBackgroundLocationUpdates, showCalibration;
#pragma mark Internal
// TODO: Do we need to force this onto the main thread?
- (void)shutdownLocationManager
{
[lock lock];
if (locationManager == nil) {
[lock unlock];
return;
}
if (trackingHeading) {
[locationManager stopUpdatingHeading];
}
if (trackingLocation) {
if (trackSignificantLocationChange) {
[locationManager stopMonitoringSignificantLocationChanges];
} else {
[locationManager stopUpdatingLocation];
}
}
RELEASE_TO_NIL_AUTORELEASE(locationManager);
[lock unlock];
}
- (void)dealloc
{
[self shutdownLocationManager];
[self releaseSingleshotListeners];
RELEASE_TO_NIL(locationPermissionManager);
RELEASE_TO_NIL(purpose);
RELEASE_TO_NIL(lock);
RELEASE_TO_NIL(lastLocationDict);
RELEASE_TO_NIL(authorizationCallback);
RELEASE_TO_NIL(authorizationPromise);
[super dealloc];
}
- (NSString *)apiName
{
return @"Ti.Geolocation";
}
/**
* Returns true iff the array was not nil, and all entries have now been removed.
*/
- (BOOL)releaseStoredCallbackArray:(NSMutableArray *)array
{
if (array != nil) {
for (GeolocationCallback *callback in [NSArray arrayWithArray:array]) {
[array removeObject:callback];
}
if ([array count] == 0) {
RELEASE_TO_NIL(array);
return YES;
}
}
return NO;
}
- (void)releaseSingleshotListeners
{
if ([self releaseStoredCallbackArray:singleHeading]) {
[locationManager stopUpdatingHeading];
}
if ([self releaseStoredCallbackArray:singleLocation]) {
[locationManager stopUpdatingLocation];
}
}
- (id)init
{
if (self = [super init]) {
// reasonable defaults:
// accuracy by default
accuracy = kCLLocationAccuracyThreeKilometers;
// distance filter by default is notify of all movements
distance = kCLDistanceFilterNone;
// minimum heading filter by default
heading = kCLHeadingFilterNone;
// should we show heading calibration dialog? defaults to YES
showCalibration = YES;
// track all location changes by default
trackSignificantLocationChange = NO;
// activity Type by default
activityType = CLActivityTypeOther;
// pauseLocationupdateAutomatically by default NO
pauseLocationUpdateAutomatically = NO;
// Set the default based on if the user has defined a background location mode
NSArray *backgroundModes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UIBackgroundModes"];
self.allowsBackgroundLocationUpdates = ([backgroundModes containsObject:@"location"]);
// Per default, background location indicators are not visible
showBackgroundLocationIndicator = NO;
lock = [[NSRecursiveLock alloc] init];
}
return self;
}
- (CLLocationManager *)locationManager
{
[lock lock];
if (locationManager == nil) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if (!trackSignificantLocationChange) {
if (accuracy != -1) {
locationManager.desiredAccuracy = accuracy;
} else {
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
}
locationManager.distanceFilter = distance;
}
locationManager.headingFilter = heading;
if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedAlways &&
[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
NSLog(@"[WARN] Trying to use location services without requesting location permissions. Use either:\n\n"
"Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS, function(e) {\n"
"\t// Handle authorization via e.success\n"
"})\n\n"
"or\n\n"
"Ti.Geolocation.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_WHEN_IN_USE, function(e) {\n"
"\t// Handle authorization via e.success\n"
"})\nPicking the highest permission by default.");
if (![[NSBundle mainBundle] objectForInfoDictionaryKey:kTiGeolocationUsageDescriptionWhenInUse]) {
NSLog(@"[WARN] Apps targeting iOS 11 and later always have to include the \"%@\" key in the tiapp.xml <plist> section in order to use any geolocation-services. This is a constraint Apple introduced to improve user-privacy by suggesting developers to incrementally upgrade the location permissions from \"When in Use\" to \"Always\" only if necessary. You can specify the new iOS 11+ plist-key \"%@\" which is used while upgrading from \"When in Use\" to \"Always\". Use the the Ti.Geolocation.requestLocationPermissions method, which should be called before using any Ti.Geolocation related API. Please verify location permissions and call this method again.", kTiGeolocationUsageDescriptionWhenInUse, kTiGeolocationUsageDescriptionAlwaysAndWhenInUse);
}
if ([GeolocationModule hasAlwaysPermissionKeys]) {
[locationManager requestAlwaysAuthorization];
} else if ([GeolocationModule hasWhenInUsePermissionKeys]) {
[locationManager requestWhenInUseAuthorization];
} else {
NSLog(@"[ERROR] If you are only using geolocation-services *when in use*, you only need to specify the %@ key in your tiapp.xml", kTiGeolocationUsageDescriptionWhenInUse);
NSLog(@"[ERROR] If you are *always* using geolocation-servcies, you need to specify the following three keys in your tiapp.xml:\n * %@\n * %@\n * %@", kTiGeolocationUsageDescriptionWhenInUse, kTiGeolocationUsageDescriptionAlways, kTiGeolocationUsageDescriptionAlwaysAndWhenInUse);
}
}
locationManager.allowsBackgroundLocationUpdates = allowsBackgroundLocationUpdates;
locationManager.showsBackgroundLocationIndicator = showBackgroundLocationIndicator;
locationManager.activityType = activityType;
locationManager.pausesLocationUpdatesAutomatically = pauseLocationUpdateAutomatically;
if (![CLLocationManager locationServicesEnabled]) {
// NOTE: This is from the Apple example and it works well. the developer can still check for the
// property and do this message themselves before calling geo. But if they don't, we at least do it for them.
NSString *title = NSLocalizedString(@"Location Services Disabled", @"Location Services Disabled Alert Title");
NSString *msg = NSLocalizedString(@"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled.", @"Location Services Disabled Alert Message");
NSString *ok = NSLocalizedString(@"OK", @"Location Services Disabled Alert OK Button");
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:ok style:UIAlertActionStyleCancel handler:nil];
[alertController addAction:action];
[[TiApp app] showModalController:alertController animated:YES];
}
}
[lock unlock];
return locationManager;
}
- (void)startStopLocationManagerIfNeeded
{
BOOL startHeading = NO;
BOOL startLocation = NO;
// if we have queued getCurrentHeading() calls or a 'heading' event listener, startHeading
if ((singleHeading != nil && [singleHeading count] > 0) || [self _hasListeners:@"heading"]) {
startHeading = YES;
}
// if we have queued getCurrentPosition() calls or a 'location' event listener, startLocation
if ((singleLocation != nil && [singleLocation count] > 0) || [self _hasListeners:@"location"]) {
startLocation = YES;
}
// Basically we need to guard against "starting" location manager unnecessarily
// So if both are NO *and* it's already nil, return early
if (!startHeading && !startLocation && locationManager == nil) {
return;
}
// Otherwise toggle based on if we're already tracking heading/location
CLLocationManager *lm = [self locationManager];
// heading
if (startHeading && !trackingHeading) { // track heading if we aren't already...
[lm startUpdatingHeading];
trackingHeading = YES;
} else if (!startHeading && trackingHeading) { // turn off heading if we were and don't want to anymore...
trackingHeading = NO;
[lm stopUpdatingHeading];
}
// location
if (startLocation && !trackingLocation) { // track location if we aren't already...
if (trackSignificantLocationChange) {
[lm startMonitoringSignificantLocationChanges];
} else {
[lm startUpdatingLocation];
}
trackingLocation = YES;
} else if (!startLocation && trackingLocation) { // turn off location if we were and don't want to anymore...
trackingLocation = NO;
if (trackSignificantLocationChange) {
[lm stopMonitoringSignificantLocationChanges];
} else {
[lm stopUpdatingLocation];
}
}
// If we turned both heading and location off...
// TODO: Move this to top? it turns off heading/location under the covers if necessary
if (!trackingHeading && !trackingLocation) {
[self shutdownLocationManager]; // shut down the location manager
}
}
- (void)_listenerAdded:(NSString *)type count:(int)count
{
BOOL startStop = NO;
if (count == 1 && [type isEqualToString:@"heading"]) {
startStop = YES;
} else if (count == 1 && [type isEqualToString:@"location"]) {
startStop = YES;
}
if (startStop) {
TiThreadPerformOnMainThread(
^{
[self startStopLocationManagerIfNeeded];
},
NO);
}
}
- (void)_listenerRemoved:(NSString *)type count:(int)count
{
BOOL check = NO;
if (count == 0 && [type isEqualToString:@"heading"]) {
check = YES;
if (trackingHeading) {
trackingHeading = NO;
[locationManager stopUpdatingHeading];
}
} else if (count == 0 && [type isEqualToString:@"location"]) {
check = YES;
if (trackingLocation) {
trackingLocation = NO;
[locationManager stopUpdatingLocation];
}
}
if (check && ![self _hasListeners:@"heading"] && ![self _hasListeners:@"location"]) {
TiThreadPerformOnMainThread(
^{
[self startStopLocationManagerIfNeeded];
},
YES);
[self shutdownLocationManager];
trackingLocation = NO;
trackingHeading = NO;
[self releaseSingleshotListeners];
}
}
- (BOOL)headingAvailable
{
return [CLLocationManager headingAvailable];
}
#pragma mark Public APIs
- (BOOL)hasCompass
{
return [self headingAvailable];
}
GETTER_IMPL(BOOL, hasCompass, HasCompass);
- (JSValue *)reverseGeocoder:(double)latitude longitude:(double)longitude withCallback:(JSValue *)callback
{
#ifndef __clang_analyzer__ // Ignore static analyzer error here, memory will be released. See TIMOB-19444
KrollPromise *promise = [[[KrollPromise alloc] initInContext:[self currentContext]] autorelease];
ReverseGeoCallback *rcb = [[ReverseGeoCallback alloc] initWithCallback:callback andPromise:promise];
CLGeocoder *geoCoder = [[[CLGeocoder alloc] init] autorelease];
CLLocation *clLocation = [[[CLLocation alloc] initWithLatitude:latitude longitude:longitude] autorelease];
[geoCoder reverseGeocodeLocation:clLocation
preferredLocale:[NSLocale currentLocale]
completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError *_Nullable error) {
if (error != nil) {
[rcb requestError:error];
} else {
NSMutableDictionary *events = [TiUtils dictionaryWithCode:0 message:nil];
NSMutableArray<NSMutableDictionary *> *places = [NSMutableArray array];
for (CLPlacemark *placemark in placemarks) {
NSMutableDictionary *place = [NSMutableDictionary dictionary];
if (placemark.thoroughfare) {
place[@"street"] = placemark.thoroughfare;
}
if (placemark.locality) {
place[@"city"] = placemark.locality;
}
if (placemark.administrativeArea) {
place[@"state"] = placemark.administrativeArea;
}
if (placemark.country) {
place[@"country"] = placemark.country;
}
if (placemark.postalCode) {
place[@"postalCode"] = placemark.postalCode;
}
if (placemark.ISOcountryCode) {
place[@"countryCode"] = placemark.ISOcountryCode;
}
if (placemark.location) {
place[@"latitude"] = @(placemark.location.coordinate.latitude);
place[@"longitude"] = @(placemark.location.coordinate.longitude);
}
if (placemark.postalAddress) {
place[@"address"] = [CNPostalAddressFormatter stringFromPostalAddress:placemark.postalAddress style:CNPostalAddressFormatterStyleMailingAddress];
}
[places addObject:place];
}
events[@"places"] = places;
[rcb requestSuccess:events];
}
}];
return promise.JSValue;
#endif
}
- (JSValue *)forwardGeocoder:(NSString *)address withCallback:(JSValue *)callback
{
#ifndef __clang_analyzer__ // Ignore static analyzer error here, memory will be released. See TIMOB-19444
KrollPromise *promise = [[[KrollPromise alloc] initInContext:[self currentContext]] autorelease];
ForwardGeoCallback *fcb = [[ForwardGeoCallback alloc] initWithCallback:callback andPromise:promise];
CLGeocoder *geoCoder = [[[CLGeocoder alloc] init] autorelease];
[geoCoder geocodeAddressString:address
inRegion:nil
preferredLocale:[NSLocale currentLocale]
completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError *_Nullable error) {
if (error != nil) {
[fcb requestError:error];
} else {
NSMutableDictionary *events = [TiUtils dictionaryWithCode:0 message:nil];
CLPlacemark *placemark = [placemarks firstObject]; // For forward geocode, take first object only
if (placemark.location) {
events[@"latitude"] = @(placemark.location.coordinate.latitude);
events[@"longitude"] = @(placemark.location.coordinate.longitude);
}
[fcb requestSuccess:events];
}
}];
return promise.JSValue;
#endif
}
- (JSValue *)getCurrentHeading:(JSValue *)callback
{
ENSURE_UI_THREAD(getCurrentHeading, callback);
JSContext *context = [self currentContext];
KrollPromise *promise = [[[KrollPromise alloc] initInContext:context] autorelease];
HeadingCallback *cb = [[HeadingCallback alloc] initWithCallback:callback andPromise:promise];
if (![self headingAvailable]) {
// if we can't track heading we'll never fire unless we do so manually here
NSMutableDictionary *event = [TiUtils dictionaryWithCode:1 message:@"The location manager is not able to generate heading-related events on this device"];
[cb fireEvent:event withProxy:self];
} else {
// We need to hold on to the promise and optional callback in some dictionary or pair object
if (singleHeading == nil) {
singleHeading = [[NSMutableArray alloc] initWithCapacity:1];
}
[singleHeading addObject:cb];
[self startStopLocationManagerIfNeeded];
}
return promise.JSValue;
}
- (JSValue *)getCurrentPosition:(JSValue *)callback
{
ENSURE_UI_THREAD(getCurrentPosition, callback);
KrollPromise *promise = [[[KrollPromise alloc] initInContext:[self currentContext]] autorelease];
// If the location updates are started, invoke the callback directly.
if (locationManager != nil && locationManager.location != nil && trackingLocation) {
CLLocation *currentLocation = locationManager.location;
NSMutableDictionary *event = [TiUtils dictionaryWithCode:0 message:nil];
event[@"coords"] = [self locationDictionary:currentLocation];
event[@"type"] = @"location";
event[@"source"] = self;
// FIXME queue this up to happen async
if (callback != nil && ![callback isUndefined]) {
[callback callWithArguments:@[ event ]];
}
[promise resolve:@[ event ]];
}
// Otherwise, start the location manager.
else {
if (singleLocation == nil) {
singleLocation = [[NSMutableArray alloc] initWithCapacity:1];
}
PositionCallback *cb = [[PositionCallback alloc] initWithCallback:callback andPromise:promise];
[singleLocation addObject:cb];
[self startStopLocationManagerIfNeeded];
}
return promise.JSValue;
}
- (NSString *)lastGeolocation
{
return [TiUtils jsonStringify:lastLocationDict error:nil];
}
- (CLLocationAccuracy)accuracy
{
return accuracy;
}
- (void)setAccuracy:(CLLocationAccuracy)value
{
ENSURE_UI_THREAD(setAccuracy, value);
accuracy = value;
// don't prematurely start it
if (locationManager != nil) {
[locationManager setDesiredAccuracy:accuracy];
}
}
READWRITE_IMPL(CLLocationAccuracy, accuracy, Accuracy);
- (CLLocationDistance)distanceFilter
{
return distance;
}
- (void)setDistanceFilter:(CLLocationDistance)value
{
ENSURE_UI_THREAD(setDistanceFilter, value);
distance = value;
// don't prematurely start it
if (locationManager != nil) {
[locationManager setDistanceFilter:distance];
}
}
READWRITE_IMPL(CLLocationDistance, distanceFilter, DistanceFilter);
- (CLLocationDegrees)headingFilter
{
return heading;
}
- (void)setHeadingFilter:(CLLocationDegrees)value
{
ENSURE_UI_THREAD(setHeadingFilter, value);
heading = value;
// don't prematurely start it
if (locationManager != nil) {
[locationManager setHeadingFilter:heading];
}
}
READWRITE_IMPL(CLLocationDegrees, headingFilter, HeadingFilter);
- (BOOL)showBackgroundLocationIndicator
{
return showBackgroundLocationIndicator;
}
- (void)setShowBackgroundLocationIndicator:(BOOL)value
{
showBackgroundLocationIndicator = value;
}
READWRITE_IMPL(bool, showBackgroundLocationIndicator, ShowBackgroundLocationIndicator);
- (bool)locationServicesEnabled
{
return [CLLocationManager locationServicesEnabled];
}
GETTER_IMPL(bool, locationServicesEnabled, LocationServicesEnabled);
- (CLAuthorizationStatus)locationServicesAuthorization
{
return [CLLocationManager authorizationStatus];
}
GETTER_IMPL(CLAuthorizationStatus, locationServicesAuthorization, LocationServicesAuthorization);
- (bool)trackSignificantLocationChange
{
return trackSignificantLocationChange;
}
- (void)setTrackSignificantLocationChange:(bool)newval
{
if ([CLLocationManager significantLocationChangeMonitoringAvailable]) {
if (newval != trackSignificantLocationChange) {
if (trackingLocation && locationManager != nil) {
[lock lock];
[self shutdownLocationManager];
trackingHeading = NO;
trackingLocation = NO;
trackSignificantLocationChange = newval;
[lock unlock];
TiThreadPerformOnMainThread(
^{
[self startStopLocationManagerIfNeeded];
},
NO);
return;
}
}
trackSignificantLocationChange = newval;
} else {
trackSignificantLocationChange = NO;
DebugLog(@"[WARN] Ti.Geolocation.setTrackSignificantLocationChange is not supported on this device.");
}
}
READWRITE_IMPL(bool, trackSignificantLocationChange, TrackSignificantLocationChange);
// Activity Type for CLlocationManager.
- (CLActivityType)activityType
{
return activityType;
}
- (void)setActivityType:(CLActivityType)value
{
activityType = value;
TiThreadPerformOnMainThread(
^{
[locationManager setActivityType:activityType];
},
NO);
}
READWRITE_IMPL(CLActivityType, activityType, ActivityType);
// Flag to decide whether or not the app should continue to send location updates while the app is in background.
- (bool)pauseLocationUpdateAutomatically
{
return pauseLocationUpdateAutomatically;
}
- (void)setPauseLocationUpdateAutomatically:(bool)value
{
pauseLocationUpdateAutomatically = value;
TiThreadPerformOnMainThread(
^{
[locationManager setPausesLocationUpdatesAutomatically:pauseLocationUpdateAutomatically];
},
NO);
}
READWRITE_IMPL(bool, pauseLocationUpdateAutomatically, PauseLocationUpdateAutomatically);
- (void)restart:(id)arg
{
[lock lock];
[self shutdownLocationManager];
trackingHeading = NO;
trackingLocation = NO;
[lock unlock];
// must be on UI thread
TiThreadPerformOnMainThread(
^{
[self startStopLocationManagerIfNeeded];
},
NO);
}
MAKE_SYSTEM_PROP_DBL(ACCURACY_BEST, kCLLocationAccuracyBest);
MAKE_SYSTEM_PROP_DBL(ACCURACY_HIGH, kCLLocationAccuracyBest);
MAKE_SYSTEM_PROP_DBL(ACCURACY_NEAREST_TEN_METERS, kCLLocationAccuracyNearestTenMeters);
MAKE_SYSTEM_PROP_DBL(ACCURACY_HUNDRED_METERS, kCLLocationAccuracyHundredMeters);
MAKE_SYSTEM_PROP_DBL(ACCURACY_KILOMETER, kCLLocationAccuracyKilometer);
MAKE_SYSTEM_PROP_DBL(ACCURACY_THREE_KILOMETERS, kCLLocationAccuracyThreeKilometers);
MAKE_SYSTEM_PROP_DBL(ACCURACY_LOW, kCLLocationAccuracyThreeKilometers);
MAKE_SYSTEM_PROP_DBL(ACCURACY_BEST_FOR_NAVIGATION, kCLLocationAccuracyBestForNavigation);
MAKE_SYSTEM_PROP_DBL(ACCURACY_REDUCED, kCLLocationAccuracyReduced);
MAKE_SYSTEM_PROP(ACCURACY_AUTHORIZATION_FULL, CLAccuracyAuthorizationFullAccuracy);
MAKE_SYSTEM_PROP(ACCURACY_AUTHORIZATION_REDUCED, CLAccuracyAuthorizationReducedAccuracy);
MAKE_SYSTEM_PROP(AUTHORIZATION_UNKNOWN, kCLAuthorizationStatusNotDetermined);
MAKE_SYSTEM_PROP(AUTHORIZATION_AUTHORIZED, kCLAuthorizationStatusAuthorizedAlways);
MAKE_SYSTEM_PROP(AUTHORIZATION_WHEN_IN_USE, kCLAuthorizationStatusAuthorizedWhenInUse);
MAKE_SYSTEM_PROP(AUTHORIZATION_ALWAYS, kCLAuthorizationStatusAuthorizedAlways);
MAKE_SYSTEM_PROP(AUTHORIZATION_DENIED, kCLAuthorizationStatusDenied);
MAKE_SYSTEM_PROP(AUTHORIZATION_RESTRICTED, kCLAuthorizationStatusRestricted);
MAKE_SYSTEM_PROP(ERROR_LOCATION_UNKNOWN, kCLErrorLocationUnknown);
MAKE_SYSTEM_PROP(ERROR_DENIED, kCLErrorDenied);
MAKE_SYSTEM_PROP(ERROR_NETWORK, kCLErrorNetwork);
MAKE_SYSTEM_PROP(ERROR_HEADING_FAILURE, kCLErrorHeadingFailure);
MAKE_SYSTEM_PROP(ERROR_REGION_MONITORING_DENIED, kCLErrorRegionMonitoringDenied);
MAKE_SYSTEM_PROP(ERROR_REGION_MONITORING_FAILURE, kCLErrorRegionMonitoringFailure);
MAKE_SYSTEM_PROP(ERROR_REGION_MONITORING_DELAYED, kCLErrorRegionMonitoringSetupDelayed);
MAKE_SYSTEM_PROP(ACTIVITYTYPE_OTHER, CLActivityTypeOther);
MAKE_SYSTEM_PROP(ACTIVITYTYPE_AUTOMOTIVE_NAVIGATION, CLActivityTypeAutomotiveNavigation);
MAKE_SYSTEM_PROP(ACTIVITYTYPE_FITNESS, CLActivityTypeFitness);
MAKE_SYSTEM_PROP(ACTIVITYTYPE_OTHER_NAVIGATION, CLActivityTypeOtherNavigation);
- (CLLocationManager *)locationPermissionManager
{
// if we don't have an instance, create it
if (locationPermissionManager == nil) {
locationPermissionManager = [[CLLocationManager alloc] init];
locationPermissionManager.delegate = self;
}
return locationPermissionManager;
}
- (bool)hasLocationPermissions:(CLAuthorizationStatus)authorizationType
{
if (!CLLocationManager.locationServicesEnabled) {
return false;
}
CLAuthorizationStatus currentPermissionLevel = CLLocationManager.authorizationStatus;
// FIXME: If user does not supply the value, what should we do?
// Basically if they give a value other than AUTHORIZATION_ALWAYS, assume WHEN_IN_USE
CLAuthorizationStatus requestedPermissionLevel = (authorizationType == kCLAuthorizationStatusAuthorizedAlways) ? kCLAuthorizationStatusAuthorizedAlways : kCLAuthorizationStatusAuthorizedWhenInUse;
return currentPermissionLevel == requestedPermissionLevel;
}
- (JSValue *)requestLocationPermissions:(CLAuthorizationStatus)authorizationType withCallback:(JSValue *)callback
{
// Store the authorization callback for later usage
// FIXME: What about multiple calls before resolution. We should store in an array like we do for getCurrentPosition
if (callback != nil && ![callback isUndefined]) {
if (authorizationCallback != nil) {
[authorizationCallback release];
authorizationCallback = nil;
}
authorizationCallback = [callback retain];
}
// Promise to return
KrollPromise *promise = [[[KrollPromise alloc] initInContext:[self currentContext]] autorelease];
if (authorizationPromise != nil) {
[authorizationPromise release];
authorizationPromise = nil;
}
authorizationPromise = [promise retain];
requestedAuthorizationStatus = authorizationType;
CLAuthorizationStatus currentPermissionLevel = [CLLocationManager authorizationStatus];
BOOL permissionsGranted = currentPermissionLevel == requestedAuthorizationStatus;
// For iOS < 11, already granted permissions will return with success immediately
if (permissionsGranted) {
[self executeAndReleaseCallbackWithCode:0 andMessage:nil];
return promise.JSValue;
} else if (currentPermissionLevel == kCLAuthorizationStatusDenied) {
[self executeAndReleaseCallbackWithCode:1 andMessage:@"The user denied access to use location services."];
return promise.JSValue;
}
NSString *errorMessage = nil;
if (requestedAuthorizationStatus == kCLAuthorizationStatusAuthorizedWhenInUse) {
if ([GeolocationModule hasWhenInUsePermissionKeys]) {
if (currentPermissionLevel == kCLAuthorizationStatusAuthorizedAlways) {
errorMessage = @"Cannot change already granted permission from AUTHORIZATION_ALWAYS to the lower permission-level AUTHORIZATION_WHEN_IN_USE";
} else {
TiThreadPerformOnMainThread(
^{
[[self locationPermissionManager] requestWhenInUseAuthorization];
},
NO);
}
} else {
errorMessage = [[NSString alloc] initWithFormat:@"The %@ key must be defined in your tiapp.xml in order to request this permission",
kTiGeolocationUsageDescriptionWhenInUse];
}
}
if (requestedAuthorizationStatus == kCLAuthorizationStatusAuthorizedAlways) {
if ([GeolocationModule hasAlwaysPermissionKeys]) {
TiThreadPerformOnMainThread(
^{
[[self locationPermissionManager] requestAlwaysAuthorization];
},
NO);
} else {
errorMessage = [[NSString alloc] initWithFormat:
@"The %@, %@ and %@ (iOS 11+) key must be defined in your tiapp.xml in order to request this permission.",
kTiGeolocationUsageDescriptionWhenInUse,
kTiGeolocationUsageDescriptionAlways,
kTiGeolocationUsageDescriptionAlwaysAndWhenInUse];
}
}
if (errorMessage != nil) {
NSLog(@"[ERROR] %@", errorMessage);
[self executeAndReleaseCallbackWithCode:1 andMessage:errorMessage];
RELEASE_TO_NIL(errorMessage);
}
return promise.JSValue;
}
- (void)requestTemporaryFullAccuracyAuthorization:(NSString *)purposeKey withCallback:(JSValue *)callback
{
if (![TiUtils isIOSVersionOrGreater:@"14.0"]) {
NSMutableDictionary *propertiesDict = [TiUtils dictionaryWithCode:1 message:@"Supported on iOS 14+"];
[callback callWithArguments:@[ propertiesDict ]];
return;
}
NSDictionary *descriptionDict = [[NSBundle mainBundle] objectForInfoDictionaryKey:kTiGeolocationTemporaryUsageDescriptionDictionary];
if (!descriptionDict || ![descriptionDict valueForKey:purposeKey]) {
DebugLog(@"[WARN] Add %@ key with purpose key %@ in info.plist", kTiGeolocationTemporaryUsageDescriptionDictionary, purposeKey);
NSString *msg = [NSString stringWithFormat:@"Add %@ key with purpose key %@ in info.plist", kTiGeolocationTemporaryUsageDescriptionDictionary, purposeKey];
NSMutableDictionary *propertiesDict = [TiUtils dictionaryWithCode:1 message:msg];
[callback callWithArguments:@[ propertiesDict ]];
return;
}
[[self locationPermissionManager] requestTemporaryFullAccuracyAuthorizationWithPurposeKey:purposeKey
completion:^(NSError *_Nullable error) {
NSMutableDictionary *propertiesDict = [TiUtils dictionaryWithCode:0 message:nil];
if (error != nil) {
propertiesDict = [TiUtils dictionaryWithCode:1 message:error.description];
} else {
propertiesDict[@"accuracyAuthorization"] = @([[self locationPermissionManager] accuracyAuthorization]);
}
[callback callWithArguments:@[ propertiesDict ]];
}];
}
- (CLAccuracyAuthorization)locationAccuracyAuthorization
{
if (![TiUtils isIOSVersionOrGreater:@"14.0"]) {
DebugLog(@"[ERROR] This property is available on iOS 14 and above.");
return -1;
}
return [[self locationPermissionManager] accuracyAuthorization];
}
READWRITE_IMPL(bool, allowsBackgroundLocationUpdates, AllowsBackgroundLocationUpdates);
GETTER_IMPL(NSString *, lastGeolocation, LastGeolocation);
READWRITE_IMPL(bool, showCalibration, ShowCalibration);
#pragma mark Internal
+ (BOOL)hasAlwaysPermissionKeys
{
return [[NSBundle mainBundle] objectForInfoDictionaryKey:kTiGeolocationUsageDescriptionWhenInUse] &&
[[NSBundle mainBundle] objectForInfoDictionaryKey:kTiGeolocationUsageDescriptionAlways] &&
[[NSBundle mainBundle] objectForInfoDictionaryKey:kTiGeolocationUsageDescriptionAlwaysAndWhenInUse];
}
+ (BOOL)hasWhenInUsePermissionKeys
{
return [[NSBundle mainBundle] objectForInfoDictionaryKey:kTiGeolocationUsageDescriptionWhenInUse] != nil;
}
- (void)executeAndReleaseCallbackWithCode:(NSInteger)code andMessage:(NSString *)message withDict:(NSDictionary *)dict
{
NSMutableDictionary *fullDict = [TiUtils dictionaryWithCode:code message:message];
if (dict != nil) {
[fullDict addEntriesFromDictionary:dict];
}
NSArray *invocationArray = @[ fullDict ];
if (authorizationPromise != nil) {
if (code == 0) {
[authorizationPromise resolve:invocationArray];
} else {
[authorizationPromise rejectWithErrorMessage:message];
}
[authorizationPromise release];
authorizationPromise = nil;
}
if (authorizationCallback != nil) {
if (![authorizationCallback isUndefined]) {
[authorizationCallback callWithArguments:invocationArray];
}
// release the stored callback
[authorizationCallback release];
authorizationCallback = nil;
}
}
- (void)executeAndReleaseCallbackWithCode:(NSInteger)code andMessage:(NSString *)message
{
[self executeAndReleaseCallbackWithCode:code andMessage:message withDict:nil];
}
- (NSDictionary *)locationDictionary:(CLLocation *)newLocation;
{
if ([newLocation timestamp] == 0) {
// this happens when the location object is essentially null (as in no location)
return nil;
}
CLLocationCoordinate2D latlon = [newLocation coordinate];
NSMutableDictionary *data = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:latlon.latitude], @"latitude",
[NSNumber numberWithFloat:latlon.longitude], @"longitude",
[NSNumber numberWithFloat:[newLocation altitude]], @"altitude",
[NSNumber numberWithFloat:[newLocation horizontalAccuracy]], @"accuracy",
[NSNumber numberWithFloat:[newLocation verticalAccuracy]], @"altitudeAccuracy",
[NSNumber numberWithFloat:[newLocation course]], @"heading",
[NSNumber numberWithFloat:[newLocation speed]], @"speed",
[NSNumber numberWithLongLong:(long long)([[newLocation timestamp] timeIntervalSince1970] * 1000)], @"timestamp",
nil];
data[@"floor"] = @{ @"level" : [NSNumber numberWithInteger:[[newLocation floor] level]] };
return data;
}
- (NSDictionary *)headingDictionary:(CLHeading *)newHeading
{
long long ts = (long long)[[newHeading timestamp] timeIntervalSince1970] * 1000;
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:[newHeading magneticHeading]], @"magneticHeading",
[NSNumber numberWithDouble:[newHeading trueHeading]], @"trueHeading",
[NSNumber numberWithDouble:[newHeading headingAccuracy]], @"accuracy",
[NSNumber numberWithLongLong:ts], @"timestamp",
[NSNumber numberWithDouble:[newHeading x]], @"x",
[NSNumber numberWithDouble:[newHeading y]], @"y",
[NSNumber numberWithDouble:[newHeading z]], @"z",
nil];
return data;
}
#pragma mark Single Shot Handling
- (BOOL)fireSingleShotLocationIfNeeded:(NSDictionary *)event stopIfNeeded:(BOOL)stopIfNeeded
{
// check to see if we have any single shot location callbacks
if (singleLocation != nil) {
for (PositionCallback *cb in singleLocation) {
[cb fireEvent:event withProxy:self];
}
// after firing, we remove them
RELEASE_TO_NIL(singleLocation);
// check to make sure we don't need to stop after the single shot
if (stopIfNeeded) {
[self startStopLocationManagerIfNeeded];
}