forked from tidev/titanium-sdk
/
GeolocationModule.m
1189 lines (1010 loc) · 35.4 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
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2014 by Appcelerator, Inc. 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 "TiApp.h"
#import "TiEvaluator.h"
#import "SBJSON.h"
#import <sys/utsname.h>
#import "NSData+Additions.h"
#import "APSAnalytics.h"
#import "AnalyticsModule.h"
extern NSString * const TI_APPLICATION_GUID;
extern BOOL const TI_APPLICATION_ANALYTICS;
@interface GeolocationCallback : NSObject<APSHTTPRequestDelegate>
{
id<TiEvaluator> context;
KrollCallback *callback;
}
-(id)initWithCallback:(KrollCallback*)callback context:(id<TiEvaluator>)context;
@end
@implementation GeolocationCallback
-(id)initWithCallback:(KrollCallback*)callback_ context:(id<TiEvaluator>)context_
{
//Ignore analyzer warning here. Delegate will call autorelease onLoad or onError.
if (self = [super init])
{
callback = [callback_ retain];
context = [context_ retain];
}
return self;
}
-(void)dealloc
{
RELEASE_TO_NIL(callback);
RELEASE_TO_NIL(context);
[super dealloc];
}
-(void)start:(NSDictionary*)params
{
// https://api.appcelerator.net/p/v1/geo
NSString *kGeolocationURL = stringWithHexString(@"68747470733a2f2f6170692e61707063656c657261746f722e6e65742f702f76312f67656f");
NSMutableString *url = [[[NSMutableString alloc] init] autorelease];
[url appendString:kGeolocationURL];
[url appendString:@"?"];
for (id key in params)
{
NSString *value = [TiUtils stringValue:[params objectForKey:key]];
[url appendFormat:@"%@=%@&",key,[value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
APSHTTPRequest *req = [[APSHTTPRequest alloc] init];
[req addRequestHeader:@"User-Agent" value:[[TiApp app] userAgent]];
[req setUrl:[NSURL URLWithString:url]];
[req setDelegate:self];
[req setMethod:@"GET"];
// Place it in the main thread since we're not using a queue and yet we need the
// delegate methods to be called...
TiThreadPerformOnMainThread(^{
[req send];
[req autorelease];
}, NO);
}
-(void)requestSuccess:(NSString*)data
{
}
-(void)requestError:(NSError*)error
{
NSDictionary *event = [TiUtils dictionaryWithCode:[error code] message:[TiUtils messageFromError:error]];
[context fireEvent:callback withObject:event remove:NO thisObject:nil];
}
-(void)request:(APSHTTPRequest*)request onLoad:(APSHTTPResponse*)response
{
[[TiApp app] stopNetwork];
if (request!=nil && [response error]==nil)
{
NSString *data = [response responseString];
[self requestSuccess:data];
}
else
{
[self requestError:[response error]];
}
[self autorelease];
}
-(void)request:(APSHTTPRequest *)request onError:(APSHTTPResponse *)response
{
[[TiApp app] stopNetwork];
[self requestError:[response error]];
[self autorelease];
}
@end
@interface ForwardGeoCallback : GeolocationCallback
@end
@interface ReverseGeoCallback : GeolocationCallback
@end
@implementation ForwardGeoCallback
-(void)requestSuccess:(NSString*)locationString
{
NSMutableDictionary *event = nil;
NSArray *listItems = [locationString componentsSeparatedByString:@","];
if([listItems count] == 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"])
{
id accuracy = [listItems objectAtIndex:1];
id latitude = [listItems objectAtIndex:2];
id longitude = [listItems objectAtIndex:3];
event = [TiUtils dictionaryWithCode:0 message:nil];
[event setObject:accuracy forKey:@"accuracy"];
[event setObject:latitude forKey:@"latitude"];
[event setObject:longitude forKey:@"longitude"];
}
else
{
//TODO: better error handling
event = [TiUtils dictionaryWithCode:-1 message:@"error obtaining geolocation"];
}
[context fireEvent:callback withObject:event remove:NO thisObject:nil];
}
@end
@implementation ReverseGeoCallback
-(void)requestSuccess:(NSString*)locationString
{
SBJSON *json = [[SBJSON alloc] init];
NSError * error = nil;
id event = [json fragmentWithString:locationString error:&error];
[json release];
if (error != nil) {
[self requestError:error];
}
else {
BOOL success = [TiUtils boolValue:@"success" properties:event def:YES];
NSMutableDictionary * revisedEvent = [TiUtils dictionaryWithCode:success?0:-1 message:success?nil:@"error reverse geocoding"];
[revisedEvent setValuesForKeysWithDictionary:event];
[context fireEvent:callback withObject:revisedEvent remove:NO thisObject:nil];
}
}
@end
@implementation GeolocationModule
#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)_destroy
{
[self shutdownLocationManager];
RELEASE_TO_NIL(tempManager);
RELEASE_TO_NIL(locationPermissionManager);
RELEASE_TO_NIL(singleHeading);
RELEASE_TO_NIL(singleLocation);
RELEASE_TO_NIL(purpose);
RELEASE_TO_NIL(lock);
RELEASE_TO_NIL(lastLocationDict);
[super _destroy];
}
-(NSString*)apiName
{
return @"Ti.Geolocation";
}
-(void)contextWasShutdown:(KrollBridge*)bridge
{
if (singleHeading!=nil)
{
for (KrollCallback *callback in [NSArray arrayWithArray:singleHeading])
{
KrollContext *ctx = (KrollContext*)[callback context];
if ([bridge krollContext] == ctx)
{
[singleHeading removeObject:callback];
}
}
if ([singleHeading count]==0)
{
RELEASE_TO_NIL(singleHeading);
[locationManager stopUpdatingHeading];
}
}
if (singleLocation!=nil)
{
for (KrollCallback *callback in [NSArray arrayWithArray:singleLocation])
{
KrollContext *ctx = (KrollContext*)[callback context];
if ([bridge krollContext] == ctx)
{
[singleLocation removeObject:callback];
}
}
if ([singleLocation count]==0)
{
RELEASE_TO_NIL(singleLocation);
[locationManager stopUpdatingLocation];
}
}
}
-(void)_configure
{
// 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
calibration = 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"];
allowsBackgroundLocationUpdates = ([backgroundModes containsObject:@"location"]);
lock = [[NSRecursiveLock alloc] init];
[super _configure];
}
-(CLLocationManager*)locationManager
{
[lock lock];
if (locationManager==nil)
{
RELEASE_TO_NIL(tempManager);
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 ([TiUtils isIOS8OrGreater]) {
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]) {
[locationManager requestAlwaysAuthorization];
} else if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
[locationManager requestWhenInUseAuthorization];
} else {
NSLog(@"[ERROR] The keys NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription are not defined in your tiapp.xml. Starting with iOS8 this is required.");
}
} else {
if (purpose != nil) {
DebugLog(@"[WARN] The Ti.Geolocation.purpose property is deprecated. On iOS6 and above include the NSLocationUsageDescription key in your Info.plist");
if ([locationManager respondsToSelector:@selector(setPurpose:)]) {
[locationManager performSelector:@selector(setPurpose:) withObject:purpose];
}
}
}
//This is set to NO by default for > iOS9.
if ([TiUtils isIOS9OrGreater]) {
#if IS_XCODE_7
locationManager.allowsBackgroundLocationUpdates = allowsBackgroundLocationUpdates;
#endif
}
locationManager.activityType = activityType;
locationManager.pausesLocationUpdatesAutomatically = pauseLocationUpdateAutomatically;
if ([CLLocationManager locationServicesEnabled]== NO)
{
//NOTE: this is from Apple example from LocateMe 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");
UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:ok otherButtonTitles:nil];
[servicesDisabledAlert show];
[servicesDisabledAlert release];
}
}
[lock unlock];
return locationManager;
}
// this is useful for a few methods below that need to use an instance but we
// don't necessarily want to hold on to this guy
-(CLLocationManager*)tempLocationManager
{
if (locationManager!=nil)
{
// if we have an instance, just use it
return locationManager;
}
if (tempManager == nil) {
tempManager = [[CLLocationManager alloc] init];
}
return tempManager;
}
-(void)startStopLocationManagerIfNeeded
{
BOOL startHeading = NO;
BOOL startLocation = NO;
if (singleHeading!=nil && [singleHeading count] > 0)
{
startHeading = YES;
}
if (singleLocation!=nil && [singleLocation count] > 0)
{
startLocation = YES;
}
if (!startHeading && [self _hasListeners:@"heading"])
{
startHeading = YES;
}
if (!startLocation && [self _hasListeners:@"location"])
{
startLocation = YES;
}
if (startHeading || startLocation)
{
CLLocationManager *lm = [self locationManager];
if (startHeading && trackingHeading==NO)
{
[lm startUpdatingHeading];
trackingHeading = YES;
}
if (startLocation && trackingLocation==NO)
{
if (trackSignificantLocationChange) {
[lm startMonitoringSignificantLocationChanges];
}
else{
[lm startUpdatingLocation];
}
trackingLocation = YES;
}
}
else if ((!startHeading || !startLocation) && locationManager!=nil)
{
CLLocationManager *lm = [self locationManager];
if (startHeading==NO && trackingHeading)
{
trackingHeading = NO;
[lm stopUpdatingHeading];
}
if (startLocation==NO && trackingLocation)
{
trackingLocation = NO;
if (trackSignificantLocationChange){
[lm stopMonitoringSignificantLocationChanges];
}
else{
[lm stopUpdatingLocation];
}
}
if ((startHeading==NO && startLocation==NO) ||
(trackingHeading==NO && trackingLocation==NO))
{
[self shutdownLocationManager];
trackingLocation = NO;
trackingHeading = NO;
}
}
}
-(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;
RELEASE_TO_NIL(singleHeading);
RELEASE_TO_NIL(singleLocation);
}
}
-(BOOL)headingAvailable
{
return [CLLocationManager headingAvailable];
}
#pragma mark Public APIs
-(NSNumber*)hasCompass
{
UIDevice * theDevice = [UIDevice currentDevice];
NSString* version = [theDevice systemVersion];
BOOL headingAvailableBool = [self headingAvailable];
if (headingAvailableBool)
{
struct utsname u;
uname(&u);
if (!strcmp(u.machine, "i386"))
{
// 3.0 simulator headingAvailable will report YES but its not really available except post 3.0
headingAvailableBool = [version hasPrefix:@"3.0"] ? NO : [CLLocationManager headingAvailable];
}
}
return NUMBOOL(headingAvailableBool);
}
-(void)performGeo:(NSString*)direction address:(NSString*)address callback:(GeolocationCallback*)callback
{
[[TiApp app] startNetwork];
id aguid = TI_APPLICATION_GUID;
id sid = [[TiApp app] sessionId];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
direction, @"d",
aguid,@"aguid",
[TiUtils appIdentifier],@"mid",
sid,@"sid",
address,@"q",
[[NSLocale currentLocale] objectForKey: NSLocaleCountryCode],@"c",
nil];
[callback start:params];
}
-(void)reverseGeocoder:(id)args
{
ENSURE_ARG_COUNT(args,3);
KrollCallback *callback = [args objectAtIndex:2];
ENSURE_TYPE(callback,KrollCallback);
#ifndef __clang_analyzer__ //ignore static analyzer error here, memory will be released
CGFloat lat = [TiUtils floatValue:[args objectAtIndex:0]];
CGFloat lon = [TiUtils floatValue:[args objectAtIndex:1]];
ReverseGeoCallback *rcb = [[ReverseGeoCallback alloc] initWithCallback:callback context:[self executionContext]];
[self performGeo:@"r" address:[NSString stringWithFormat:@"%f,%f",lat,lon] callback:rcb];
#endif
}
-(void)forwardGeocoder:(id)args
{
ENSURE_ARG_COUNT(args,2);
KrollCallback *callback = [args objectAtIndex:1];
ENSURE_TYPE(callback,KrollCallback);
#ifndef __clang_analyzer__ //ignore static analyzer error here, memory will be released
ForwardGeoCallback *fcb = [[ForwardGeoCallback alloc] initWithCallback:callback context:[self executionContext]];
[self performGeo:@"f" address:[TiUtils stringValue:[args objectAtIndex:0]] callback:fcb];
#endif
}
-(void)getCurrentHeading:(id)callback
{
ENSURE_SINGLE_ARG(callback,KrollCallback);
ENSURE_UI_THREAD(getCurrentHeading,callback);
if (singleHeading==nil)
{
singleHeading = [[NSMutableArray alloc] initWithCapacity:1];
}
[singleHeading addObject:callback];
[self startStopLocationManagerIfNeeded];
}
-(void)getCurrentPosition:(id)callback
{
ENSURE_SINGLE_ARG(callback,KrollCallback);
ENSURE_UI_THREAD(getCurrentPosition,callback);
// If the location updates are started, invoke the callback directly.
if (locationManager != nil && locationManager.location != nil && trackingLocation == YES ) {
CLLocation *currentLocation = locationManager.location;
NSMutableDictionary *event = [TiUtils dictionaryWithCode:0 message:nil];
[event setObject:[self locationDictionary:currentLocation] forKey:@"coords"];
[self _fireEventToListener:@"location" withObject:event listener:callback thisObject:nil];
}
// Otherwise, start the location manager.
else {
if (singleLocation==nil)
{
singleLocation = [[NSMutableArray alloc] initWithCapacity:1];
}
[singleLocation addObject:callback];
[self startStopLocationManagerIfNeeded];
}
}
-(NSString *)lastGeolocation
{
SBJSON *json = [[SBJSON alloc] init];
NSString * result = [json stringWithObject:lastLocationDict error:nil];
[json release];
return result;
}
-(NSNumber*)highAccuracy
{
return NUMBOOL(accuracy==kCLLocationAccuracyBest);
}
-(void)setHighAccuracy:(NSNumber *)value
{
ENSURE_UI_THREAD(setHighAccuracy,value);
accuracy = kCLLocationAccuracyBest;
// don't prematurely start it
if (locationManager!=nil)
{
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
}
}
-(NSNumber*)accuracy
{
return NUMDOUBLE(accuracy);
}
-(void)setAccuracy:(NSNumber *)value
{
ENSURE_UI_THREAD(setAccuracy,value);
accuracy = [TiUtils doubleValue:value];
// don't prematurely start it
if (locationManager!=nil)
{
[locationManager setDesiredAccuracy:accuracy];
}
}
-(NSNumber*)distanceFilter
{
return NUMDOUBLE(distance);
}
-(void)setDistanceFilter:(NSNumber *)value
{
ENSURE_UI_THREAD(setDistanceFilter,value);
distance = [TiUtils doubleValue:value];
// don't prematurely start it
if (locationManager!=nil)
{
[locationManager setDistanceFilter:distance];
}
}
-(NSNumber*)headingFilter
{
return NUMDOUBLE(heading);
}
-(void)setHeadingFilter:(NSNumber *)value
{
ENSURE_UI_THREAD(setHeadingFilter,value);
heading = [TiUtils doubleValue:value];
// don't prematurely start it
if (locationManager!=nil)
{
[locationManager setHeadingFilter:heading];
}
}
-(NSNumber*)allowsBackgroundLocationUpdates
{
return NUMBOOL(allowsBackgroundLocationUpdates);
}
-(void)setAllowsBackgroundLocationUpdates:(NSNumber *)value
{
allowsBackgroundLocationUpdates = [TiUtils boolValue:value];
}
-(NSNumber*)showCalibration
{
return NUMBOOL(calibration);
}
-(void)setShowCalibration:(NSNumber *)value
{
calibration = [TiUtils boolValue:value];
}
-(NSNumber*)locationServicesEnabled
{
return NUMBOOL([CLLocationManager locationServicesEnabled]);
}
-(NSNumber*)locationServicesAuthorization
{
return NUMINT([CLLocationManager authorizationStatus]);
}
-(NSNumber*)trackSignificantLocationChange
{
return NUMBOOL(trackSignificantLocationChange);
}
-(void)setTrackSignificantLocationChange:(id)value
{
if ([CLLocationManager significantLocationChangeMonitoringAvailable]) {
BOOL newval = [TiUtils boolValue:value def:YES];
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.");
}
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
// Activity Type for CLlocationManager.
-(NSNumber*)activityType
{
return NUMINT(activityType);
}
-(void)setActivityType:(NSNumber *)value
{
activityType = [TiUtils intValue:value];
TiThreadPerformOnMainThread(^{[locationManager setActivityType:activityType];}, NO);
}
// Flag to decide whether or not the app should continue to send location updates while the app is in background.
-(NSNumber*)pauseLocationUpdateAutomatically
{
return NUMBOOL(pauseLocationUpdateAutomatically);
}
-(void)setPauseLocationUpdateAutomatically:(id)value
{
pauseLocationUpdateAutomatically = [TiUtils boolValue:value];
TiThreadPerformOnMainThread(^{[locationManager setPausesLocationUpdatesAutomatically:pauseLocationUpdateAutomatically];}, NO);
}
#endif
-(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(ACCURACY_BEST_FOR_NAVIGATION, kCLLocationAccuracyBestForNavigation);//Since 2.1.3
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_2
MAKE_SYSTEM_PROP(AUTHORIZATION_UNKNOWN, kCLAuthorizationStatusNotDetermined);
MAKE_SYSTEM_PROP(AUTHORIZATION_AUTHORIZED, kCLAuthorizationStatusAuthorized);
MAKE_SYSTEM_PROP(AUTHORIZATION_DENIED, kCLAuthorizationStatusDenied);
MAKE_SYSTEM_PROP(AUTHORIZATION_RESTRICTED, kCLAuthorizationStatusRestricted);
#else
// We only need auth unknown, because that's all the system will return.
MAKE_SYSTEM_PROP(AUTHORIZATION_UNKNOWN, 0);
#endif
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);
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
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);
#endif
-(NSNumber*)AUTHORIZATION_ALWAYS
{
if ([TiUtils isIOS8OrGreater]) {
return NUMINT(kCLAuthorizationStatusAuthorizedAlways);
}
return NUMINT(0);
}
-(NSNumber*)AUTHORIZATION_WHEN_IN_USE
{
if ([TiUtils isIOS8OrGreater]) {
return NUMINT(kCLAuthorizationStatusAuthorizedWhenInUse);
}
return NUMINT(0);
}
-(CLLocationManager*)locationPermissionManager
{
// if we don't have an instance, create it
if (locationPermissionManager == nil) {
locationPermissionManager = [[CLLocationManager alloc] init];
locationPermissionManager.delegate = self;
}
return locationPermissionManager;
}
-(NSNumber*)hasLocationPermissions:(id)args
{
id value = [args objectAtIndex:0];
ENSURE_TYPE(value, NSNumber);
CLAuthorizationStatus currentPermissionLevel = [CLLocationManager authorizationStatus];
CLAuthorizationStatus requestedPermissionLevel = [TiUtils intValue: value];
BOOL locationServicesEnabled = [CLLocationManager locationServicesEnabled];
return NUMBOOL(locationServicesEnabled && currentPermissionLevel == requestedPermissionLevel);
}
-(void)requestAuthorization:(id)value
{
DEPRECATED_REPLACED(@"Geolocation.requestAuthorization", @"5.1.0", @"Geolocation.requestLocationPermissions");
[self requestLocationPermissions:@[value, [NSNull null]]];
}
-(void)requestLocationPermissions:(id)args
{
if (![TiUtils isIOS8OrGreater]) {
return;
}
id value = [args objectAtIndex:0];
ENSURE_TYPE(value, NSNumber);
// Store the authorization callback for later usage
if([args count] == 2) {
RELEASE_TO_NIL(authorizationCallback);
ENSURE_TYPE([args objectAtIndex:1], KrollCallback);
authorizationCallback = [[args objectAtIndex:1] retain];
}
CLAuthorizationStatus requested = [TiUtils intValue: value];
CLAuthorizationStatus currentPermissionLevel = [CLLocationManager authorizationStatus];
NSString *errorMessage = nil;
if(requested == kCLAuthorizationStatusAuthorizedWhenInUse) {
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
if ((currentPermissionLevel == kCLAuthorizationStatusAuthorizedAlways) ||
(currentPermissionLevel == kCLAuthorizationStatusAuthorized)) {
errorMessage = @"Cannot change already granted permission from AUTHORIZATION_ALWAYS to AUTHORIZATION_WHEN_IN_USE";
} else {
[[self locationPermissionManager] requestWhenInUseAuthorization];
}
} else {
errorMessage = @"The NSLocationWhenInUseUsageDescription key must be defined in your tiapp.xml in order to request this permission";
}
}
if ((requested == kCLAuthorizationStatusAuthorizedAlways) ||
(requested == kCLAuthorizationStatusAuthorized)) {
if ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]) {
if (currentPermissionLevel == kCLAuthorizationStatusAuthorizedWhenInUse) {
errorMessage = @"Cannot change already granted permission from AUTHORIZATION_WHEN_IN_USE to AUTHORIZATION_ALWAYS";
} else {
[[self locationPermissionManager] requestAlwaysAuthorization];
}
} else {
errorMessage = @"The NSLocationAlwaysUsageDescription key must be defined in your tiapp.xml in order to request this permission.";
}
}
[self executeAndReleaseCallbackWithCode:(errorMessage == nil) ? 0 : 1 andMessage:errorMessage];
if (errorMessage != nil) {
NSLog(@"[ERROR] %@", errorMessage);
RELEASE_TO_NIL(errorMessage);
}
}
#pragma mark Internal
-(void)executeAndReleaseCallbackWithCode:(NSInteger)code andMessage:(NSString*)message
{
if(authorizationCallback == nil) {
return;
}
NSMutableDictionary * propertiesDict = [TiUtils dictionaryWithCode:code message:message];
NSArray * invocationArray = [[NSArray alloc] initWithObjects:&propertiesDict count:1];
[authorizationCallback call:invocationArray thisObject:self];
[invocationArray release];
RELEASE_TO_NIL(message);
RELEASE_TO_NIL(authorizationCallback);
}
-(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];
if ([TiUtils isIOS8OrGreater]) {
NSDictionary *floor = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInteger:[[newLocation floor] level]],@"level",
nil];
[data setObject:floor forKey:@"floor"];
}
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 (KrollCallback *callback in singleLocation)
{
[self _fireEventToListener:@"location" withObject:event listener:callback thisObject:nil];
}
// 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];
}
return YES;
}
return NO;
}
-(BOOL)fireSingleShotHeadingIfNeeded:(NSDictionary*)event stopIfNeeded:(BOOL)stopIfNeeded
{
// check to see if we have any single shot heading callbacks
if (singleHeading!=nil)
{
for (KrollCallback *callback in singleHeading)
{
[self _fireEventToListener:@"heading" withObject:event listener:callback thisObject:nil];
}
// after firing, we remove them
RELEASE_TO_NIL(singleHeading);
// check to make sure we don't need to stop after the single shot