CDVLocation.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. #import "CDVLocation.h"
  18. #pragma mark Constants
  19. #define kPGLocationErrorDomain @"kPGLocationErrorDomain"
  20. #define kPGLocationDesiredAccuracyKey @"desiredAccuracy"
  21. #define kPGLocationForcePromptKey @"forcePrompt"
  22. #define kPGLocationDistanceFilterKey @"distanceFilter"
  23. #define kPGLocationFrequencyKey @"frequency"
  24. #pragma mark -
  25. #pragma mark Categories
  26. @implementation CDVLocationData
  27. @synthesize locationStatus, locationInfo, locationCallbacks, watchCallbacks;
  28. - (CDVLocationData*)init
  29. {
  30. self = (CDVLocationData*)[super init];
  31. if (self) {
  32. self.locationInfo = nil;
  33. self.locationCallbacks = nil;
  34. self.watchCallbacks = nil;
  35. }
  36. return self;
  37. }
  38. @end
  39. #pragma mark -
  40. #pragma mark CDVLocation
  41. @implementation CDVLocation
  42. @synthesize locationManager, locationData;
  43. - (void)pluginInitialize
  44. {
  45. self.locationManager = [[CLLocationManager alloc] init];
  46. self.locationManager.delegate = self; // Tells the location manager to send updates to this object
  47. __locationStarted = NO;
  48. __highAccuracyEnabled = NO;
  49. self.locationData = nil;
  50. }
  51. - (BOOL)isAuthorized
  52. {
  53. BOOL authorizationStatusClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+
  54. if (authorizationStatusClassPropertyAvailable) {
  55. NSUInteger authStatus = [CLLocationManager authorizationStatus];
  56. #ifdef __IPHONE_8_0
  57. if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { //iOS 8.0+
  58. return (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) || (authStatus == kCLAuthorizationStatusAuthorizedAlways) || (authStatus == kCLAuthorizationStatusNotDetermined);
  59. }
  60. #endif
  61. return (authStatus == kCLAuthorizationStatusAuthorizedAlways) || (authStatus == kCLAuthorizationStatusNotDetermined);
  62. }
  63. // by default, assume YES (for iOS < 4.2)
  64. return YES;
  65. }
  66. - (BOOL)isLocationServicesEnabled
  67. {
  68. BOOL locationServicesEnabledInstancePropertyAvailable = [self.locationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 3.x
  69. BOOL locationServicesEnabledClassPropertyAvailable = [CLLocationManager respondsToSelector:@selector(locationServicesEnabled)]; // iOS 4.x
  70. if (locationServicesEnabledClassPropertyAvailable) { // iOS 4.x
  71. return [CLLocationManager locationServicesEnabled];
  72. } else {
  73. return NO;
  74. }
  75. }
  76. - (void)startLocation:(BOOL)enableHighAccuracy
  77. {
  78. if (![self isLocationServicesEnabled]) {
  79. [self returnLocationError:PERMISSIONDENIED withMessage:@"Location services are not enabled."];
  80. return;
  81. }
  82. if (![self isAuthorized]) {
  83. NSString* message = nil;
  84. BOOL authStatusAvailable = [CLLocationManager respondsToSelector:@selector(authorizationStatus)]; // iOS 4.2+
  85. if (authStatusAvailable) {
  86. NSUInteger code = [CLLocationManager authorizationStatus];
  87. if (code == kCLAuthorizationStatusNotDetermined) {
  88. // could return POSITION_UNAVAILABLE but need to coordinate with other platforms
  89. message = @"User undecided on application's use of location services.";
  90. } else if (code == kCLAuthorizationStatusRestricted) {
  91. message = @"Application's use of location services is restricted.";
  92. }
  93. }
  94. // PERMISSIONDENIED is only PositionError that makes sense when authorization denied
  95. [self returnLocationError:PERMISSIONDENIED withMessage:message];
  96. return;
  97. }
  98. #ifdef __IPHONE_8_0
  99. NSUInteger code = [CLLocationManager authorizationStatus];
  100. if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) { //iOS8+
  101. __highAccuracyEnabled = enableHighAccuracy;
  102. if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]){
  103. [self.locationManager requestWhenInUseAuthorization];
  104. } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]) {
  105. [self.locationManager requestAlwaysAuthorization];
  106. } else {
  107. NSLog(@"[Warning] No NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key is defined in the Info.plist file.");
  108. }
  109. return;
  110. }
  111. #endif
  112. // Tell the location manager to start notifying us of location updates. We
  113. // first stop, and then start the updating to ensure we get at least one
  114. // update, even if our location did not change.
  115. [self.locationManager stopUpdatingLocation];
  116. [self.locationManager startUpdatingLocation];
  117. __locationStarted = YES;
  118. if (enableHighAccuracy) {
  119. __highAccuracyEnabled = YES;
  120. // Set distance filter to 5 for a high accuracy. Setting it to "kCLDistanceFilterNone" could provide a
  121. // higher accuracy, but it's also just spamming the callback with useless reports which drain the battery.
  122. self.locationManager.distanceFilter = 5;
  123. // Set desired accuracy to Best.
  124. self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
  125. } else {
  126. __highAccuracyEnabled = NO;
  127. self.locationManager.distanceFilter = 10;
  128. self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
  129. }
  130. }
  131. - (void)_stopLocation
  132. {
  133. if (__locationStarted) {
  134. if (![self isLocationServicesEnabled]) {
  135. return;
  136. }
  137. [self.locationManager stopUpdatingLocation];
  138. __locationStarted = NO;
  139. __highAccuracyEnabled = NO;
  140. }
  141. }
  142. - (void)locationManager:(CLLocationManager*)manager
  143. didUpdateToLocation:(CLLocation*)newLocation
  144. fromLocation:(CLLocation*)oldLocation
  145. {
  146. CDVLocationData* cData = self.locationData;
  147. cData.locationInfo = newLocation;
  148. if (self.locationData.locationCallbacks.count > 0) {
  149. for (NSString* callbackId in self.locationData.locationCallbacks) {
  150. [self returnLocationInfo:callbackId andKeepCallback:NO];
  151. }
  152. [self.locationData.locationCallbacks removeAllObjects];
  153. }
  154. if (self.locationData.watchCallbacks.count > 0) {
  155. for (NSString* timerId in self.locationData.watchCallbacks) {
  156. [self returnLocationInfo:[self.locationData.watchCallbacks objectForKey:timerId] andKeepCallback:YES];
  157. }
  158. } else {
  159. // No callbacks waiting on us anymore, turn off listening.
  160. [self _stopLocation];
  161. }
  162. }
  163. - (void)getLocation:(CDVInvokedUrlCommand*)command
  164. {
  165. [self.commandDelegate runInBackground:^{
  166. NSString* callbackId = command.callbackId;
  167. BOOL enableHighAccuracy = [[command argumentAtIndex:0] boolValue];
  168. if ([self isLocationServicesEnabled] == NO) {
  169. NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2];
  170. [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"];
  171. [posError setObject:@"Location services are disabled." forKey:@"message"];
  172. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError];
  173. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  174. } else {
  175. if (!self.locationData) {
  176. self.locationData = [[CDVLocationData alloc] init];
  177. }
  178. CDVLocationData* lData = self.locationData;
  179. if (!lData.locationCallbacks) {
  180. lData.locationCallbacks = [NSMutableArray arrayWithCapacity:1];
  181. }
  182. if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) {
  183. // add the callbackId into the array so we can call back when get data
  184. if (callbackId != nil) {
  185. [lData.locationCallbacks addObject:callbackId];
  186. }
  187. // Tell the location manager to start notifying us of heading updates
  188. [self startLocation:enableHighAccuracy];
  189. } else {
  190. [self returnLocationInfo:callbackId andKeepCallback:NO];
  191. }
  192. }
  193. }];
  194. }
  195. - (void)addWatch:(CDVInvokedUrlCommand*)command
  196. {
  197. NSString* callbackId = command.callbackId;
  198. NSString* timerId = [command argumentAtIndex:0];
  199. BOOL enableHighAccuracy = [[command argumentAtIndex:1] boolValue];
  200. if (!self.locationData) {
  201. self.locationData = [[CDVLocationData alloc] init];
  202. }
  203. CDVLocationData* lData = self.locationData;
  204. if (!lData.watchCallbacks) {
  205. lData.watchCallbacks = [NSMutableDictionary dictionaryWithCapacity:1];
  206. }
  207. // add the callbackId into the dictionary so we can call back whenever get data
  208. [lData.watchCallbacks setObject:callbackId forKey:timerId];
  209. if ([self isLocationServicesEnabled] == NO) {
  210. NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2];
  211. [posError setObject:[NSNumber numberWithInt:PERMISSIONDENIED] forKey:@"code"];
  212. [posError setObject:@"Location services are disabled." forKey:@"message"];
  213. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError];
  214. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  215. } else {
  216. if (!__locationStarted || (__highAccuracyEnabled != enableHighAccuracy)) {
  217. // Tell the location manager to start notifying us of location updates
  218. [self startLocation:enableHighAccuracy];
  219. }
  220. }
  221. }
  222. - (void)clearWatch:(CDVInvokedUrlCommand*)command
  223. {
  224. NSString* timerId = [command argumentAtIndex:0];
  225. if (self.locationData && self.locationData.watchCallbacks && [self.locationData.watchCallbacks objectForKey:timerId]) {
  226. [self.locationData.watchCallbacks removeObjectForKey:timerId];
  227. if([self.locationData.watchCallbacks count] == 0) {
  228. [self _stopLocation];
  229. }
  230. }
  231. }
  232. - (void)stopLocation:(CDVInvokedUrlCommand*)command
  233. {
  234. [self _stopLocation];
  235. }
  236. - (void)returnLocationInfo:(NSString*)callbackId andKeepCallback:(BOOL)keepCallback
  237. {
  238. CDVPluginResult* result = nil;
  239. CDVLocationData* lData = self.locationData;
  240. if (lData && !lData.locationInfo) {
  241. // return error
  242. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:POSITIONUNAVAILABLE];
  243. } else if (lData && lData.locationInfo) {
  244. CLLocation* lInfo = lData.locationInfo;
  245. NSMutableDictionary* returnInfo = [NSMutableDictionary dictionaryWithCapacity:8];
  246. NSNumber* timestamp = [NSNumber numberWithDouble:([lInfo.timestamp timeIntervalSince1970] * 1000)];
  247. [returnInfo setObject:timestamp forKey:@"timestamp"];
  248. [returnInfo setObject:[NSNumber numberWithDouble:lInfo.speed] forKey:@"velocity"];
  249. [returnInfo setObject:[NSNumber numberWithDouble:lInfo.verticalAccuracy] forKey:@"altitudeAccuracy"];
  250. [returnInfo setObject:[NSNumber numberWithDouble:lInfo.horizontalAccuracy] forKey:@"accuracy"];
  251. [returnInfo setObject:[NSNumber numberWithDouble:lInfo.course] forKey:@"heading"];
  252. [returnInfo setObject:[NSNumber numberWithDouble:lInfo.altitude] forKey:@"altitude"];
  253. [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.latitude] forKey:@"latitude"];
  254. [returnInfo setObject:[NSNumber numberWithDouble:lInfo.coordinate.longitude] forKey:@"longitude"];
  255. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:returnInfo];
  256. [result setKeepCallbackAsBool:keepCallback];
  257. }
  258. if (result) {
  259. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  260. }
  261. }
  262. - (void)returnLocationError:(NSUInteger)errorCode withMessage:(NSString*)message
  263. {
  264. NSMutableDictionary* posError = [NSMutableDictionary dictionaryWithCapacity:2];
  265. [posError setObject:[NSNumber numberWithUnsignedInteger:errorCode] forKey:@"code"];
  266. [posError setObject:message ? message:@"" forKey:@"message"];
  267. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:posError];
  268. for (NSString* callbackId in self.locationData.locationCallbacks) {
  269. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  270. }
  271. [self.locationData.locationCallbacks removeAllObjects];
  272. for (NSString* callbackId in self.locationData.watchCallbacks) {
  273. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  274. }
  275. }
  276. - (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error
  277. {
  278. NSLog(@"locationManager::didFailWithError %@", [error localizedFailureReason]);
  279. CDVLocationData* lData = self.locationData;
  280. if (lData && __locationStarted) {
  281. // TODO: probably have to once over the various error codes and return one of:
  282. // PositionError.PERMISSION_DENIED = 1;
  283. // PositionError.POSITION_UNAVAILABLE = 2;
  284. // PositionError.TIMEOUT = 3;
  285. NSUInteger positionError = POSITIONUNAVAILABLE;
  286. if (error.code == kCLErrorDenied) {
  287. positionError = PERMISSIONDENIED;
  288. }
  289. [self returnLocationError:positionError withMessage:[error localizedDescription]];
  290. }
  291. if (error.code != kCLErrorLocationUnknown) {
  292. [self.locationManager stopUpdatingLocation];
  293. __locationStarted = NO;
  294. }
  295. }
  296. //iOS8+
  297. -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
  298. {
  299. if(!__locationStarted){
  300. [self startLocation:__highAccuracyEnabled];
  301. }
  302. }
  303. - (void)dealloc
  304. {
  305. self.locationManager.delegate = nil;
  306. }
  307. - (void)onReset
  308. {
  309. [self _stopLocation];
  310. [self.locationManager stopUpdatingHeading];
  311. }
  312. @end