LocationTracker.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //
  2. // LocationTracker.m
  3. // Location
  4. //
  5. // Created by Rick
  6. // Copyright (c) 2014 Location All rights reserved.
  7. //
  8. #import "LocationTracker.h"
  9. #define LATITUDE @"latitude"
  10. #define LONGITUDE @"longitude"
  11. #define ACCURACY @"theAccuracy"
  12. #define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
  13. @implementation LocationTracker
  14. + (CLLocationManager *)sharedLocationManager {
  15. static CLLocationManager *_locationManager;
  16. @synchronized(self) {
  17. if (_locationManager == nil) {
  18. _locationManager = [[CLLocationManager alloc] init];
  19. _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
  20. _locationManager.pausesLocationUpdatesAutomatically = NO;
  21. if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
  22. //[_locationManager requestWhenInUseAuthorization];//?只在前台开启定位
  23. [_locationManager requestAlwaysAuthorization];//?在后台也可定位
  24. }
  25. // 5.iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。
  26. if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
  27. _locationManager.allowsBackgroundLocationUpdates = YES;
  28. }
  29. }
  30. }
  31. return _locationManager;
  32. }
  33. - (id)init {
  34. if (self = [super init]) {
  35. //Get the share model and also initialize myLocationArray
  36. self.shareModel = [LocationShareModel sharedModel];
  37. self.shareModel.myLocationArray = [[NSMutableArray alloc]init];
  38. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
  39. }
  40. return self;
  41. }
  42. -(void)applicationEnterBackground{
  43. CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
  44. locationManager.delegate = self;
  45. locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
  46. locationManager.distanceFilter = kCLDistanceFilterNone;//不需要移动都可以刷新
  47. if(IS_OS_8_OR_LATER) {
  48. [locationManager requestAlwaysAuthorization];
  49. }
  50. [locationManager startUpdatingLocation];
  51. //Use the BackgroundTaskManager to manage all the background Task
  52. self.shareModel.bgTask = [BackgroundTaskManager sharedBackgroundTaskManager];
  53. [self.shareModel.bgTask beginNewBackgroundTask];
  54. }
  55. - (void) restartLocationUpdates
  56. {
  57. //NSLog(@"restartLocationUpdates");
  58. if (self.shareModel.timer) {
  59. [self.shareModel.timer invalidate];
  60. self.shareModel.timer = nil;
  61. }
  62. CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
  63. locationManager.delegate = self;
  64. locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
  65. locationManager.distanceFilter = kCLDistanceFilterNone;//不需要移动都可以刷新
  66. if(IS_OS_8_OR_LATER) {
  67. [locationManager requestAlwaysAuthorization];
  68. }
  69. [locationManager startUpdatingLocation];
  70. }
  71. - (void)startLocationTracking {
  72. //NSLog(@"startLocationTracking");
  73. if ([CLLocationManager locationServicesEnabled] == NO) {
  74. //NSLog(@"locationServicesEnabled false");
  75. UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"启用位置服务" message:@"您必须启用位置服务(设置-隐私-定位服务-优易学车-始终)" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
  76. [servicesDisabledAlert show];
  77. } else {
  78. CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];
  79. if(authorizationStatus == kCLAuthorizationStatusDenied || authorizationStatus == kCLAuthorizationStatusRestricted){
  80. //NSLog(@"authorizationStatus failed");
  81. } else {
  82. //NSLog(@"authorizationStatus authorized");
  83. CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
  84. locationManager.delegate = self;
  85. locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
  86. locationManager.distanceFilter = kCLDistanceFilterNone;//不需要移动都可以刷新
  87. if(IS_OS_8_OR_LATER) {
  88. [locationManager requestAlwaysAuthorization];
  89. }
  90. [locationManager startUpdatingLocation];
  91. }
  92. }
  93. }
  94. - (void)stopLocationTracking {
  95. //NSLog(@"stopLocationTracking");
  96. if (self.shareModel.timer) {
  97. [self.shareModel.timer invalidate];
  98. self.shareModel.timer = nil;
  99. }
  100. CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
  101. [locationManager stopUpdatingLocation];
  102. }
  103. #pragma mark - CLLocationManagerDelegate Methods
  104. -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
  105. //NSLog(@"locationManager didUpdateLocations");
  106. for(int i=0;i<locations.count;i++){
  107. CLLocation * newLocation = [locations objectAtIndex:i];
  108. CLLocationCoordinate2D theLocation = newLocation.coordinate;
  109. CLLocationAccuracy theAccuracy = newLocation.horizontalAccuracy;
  110. NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
  111. if (locationAge > 30.0)
  112. {
  113. continue;
  114. }
  115. //Select only valid location and also location with good accuracy
  116. if(newLocation!=nil&&theAccuracy>0
  117. &&theAccuracy<2000
  118. &&(!(theLocation.latitude==0.0&&theLocation.longitude==0.0))){
  119. self.myLastLocation = theLocation;
  120. self.myLastLocationAccuracy= theAccuracy;
  121. NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
  122. [dict setObject:[NSNumber numberWithFloat:theLocation.latitude] forKey:@"latitude"];
  123. [dict setObject:[NSNumber numberWithFloat:theLocation.longitude] forKey:@"longitude"];
  124. [dict setObject:[NSNumber numberWithFloat:theAccuracy] forKey:@"theAccuracy"];
  125. //Add the vallid location with good accuracy into an array
  126. //Every 1 minute, I will select the best location based on accuracy and send to server
  127. [self.shareModel.myLocationArray addObject:dict];
  128. }
  129. }
  130. //If the timer still valid, return it (Will not run the code below)
  131. if (self.shareModel.timer) {
  132. return;
  133. }
  134. self.shareModel.bgTask = [BackgroundTaskManager sharedBackgroundTaskManager];
  135. [self.shareModel.bgTask beginNewBackgroundTask];
  136. //Restart the locationMaanger after 1 minute
  137. self.shareModel.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self
  138. selector:@selector(restartLocationUpdates)
  139. userInfo:nil
  140. repeats:NO];
  141. //Will only stop the locationManager after 10 seconds, so that we can get some accurate locations
  142. //The location manager will only operate for 10 seconds to save battery
  143. if (self.shareModel.delay10Seconds) {
  144. [self.shareModel.delay10Seconds invalidate];
  145. self.shareModel.delay10Seconds = nil;
  146. }
  147. self.shareModel.delay10Seconds = [NSTimer scheduledTimerWithTimeInterval:10 target:self
  148. selector:@selector(stopLocationDelayBy10Seconds)
  149. userInfo:nil
  150. repeats:NO];
  151. }
  152. //Stop the locationManager
  153. -(void)stopLocationDelayBy10Seconds{
  154. CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
  155. [locationManager stopUpdatingLocation];
  156. //NSLog(@"locationManager stop Updating after 10 seconds");
  157. }
  158. - (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error
  159. {
  160. // NSLog(@"locationManager error:%@",error);
  161. switch([error code])
  162. {
  163. case kCLErrorNetwork: // general, network-related error
  164. {
  165. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络错误" message:@"请检查网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
  166. [alert show];
  167. }
  168. break;
  169. case kCLErrorDenied:{
  170. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"启用位置服务" message:@"您必须启用位置服务(设置-隐私-定位服务-优易学车-始终)" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
  171. [alert show];
  172. }
  173. break;
  174. default:
  175. {
  176. }
  177. break;
  178. }
  179. }
  180. //Send the location to Server
  181. - (void)updateLocationToServer {
  182. //NSLog(@"updateLocationToServer");
  183. // Find the best location from the array based on accuracy
  184. NSMutableDictionary * myBestLocation = [[NSMutableDictionary alloc]init];
  185. for(int i=0;i<self.shareModel.myLocationArray.count;i++){
  186. NSMutableDictionary * currentLocation = [self.shareModel.myLocationArray objectAtIndex:i];
  187. if(i==0)
  188. myBestLocation = currentLocation;
  189. else{
  190. if([[currentLocation objectForKey:ACCURACY]floatValue]<=[[myBestLocation objectForKey:ACCURACY]floatValue]){
  191. myBestLocation = currentLocation;
  192. }
  193. }
  194. }
  195. //NSLog(@"My Best location:%@",myBestLocation);
  196. //If the array is 0, get the last location
  197. //Sometimes due to network issue or unknown reason, you could not get the location during that period, the best you can do is sending the last known location to the server
  198. if(self.shareModel.myLocationArray.count==0)
  199. {
  200. //NSLog(@"Unable to get location, use the last known location");
  201. self.myLocation=self.myLastLocation;
  202. self.myLocationAccuracy=self.myLastLocationAccuracy;
  203. }else{
  204. CLLocationCoordinate2D theBestLocation;
  205. theBestLocation.latitude =[[myBestLocation objectForKey:LATITUDE]floatValue];
  206. theBestLocation.longitude =[[myBestLocation objectForKey:LONGITUDE]floatValue];
  207. self.myLocation=theBestLocation;
  208. self.myLocationAccuracy =[[myBestLocation objectForKey:ACCURACY]floatValue];
  209. }
  210. //NSLog(@"Send to Server: Latitude(%f) Longitude(%f) Accuracy(%f)",self.myLocation.latitude, self.myLocation.longitude,self.myLocationAccuracy);
  211. //TODO: Your code to send the self.myLocation and self.myLocationAccuracy to your server
  212. //After sending the location to the server successful, remember to clear the current array with the following code. It is to make sure that you clear up old location in the array and add the new locations from locationManager
  213. [self.shareModel.myLocationArray removeAllObjects];
  214. self.shareModel.myLocationArray = nil;
  215. self.shareModel.myLocationArray = [[NSMutableArray alloc]init];
  216. }
  217. @end