LocationManager.m 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // LocationManager.m
  3. // CParam
  4. //
  5. // Created by breeze deng on 2017/8/7.
  6. // Copyright © 2017年 Breeze. All rights reserved.
  7. //
  8. #import "LocationManager.h"
  9. static LocationManager *_instance = nil;
  10. @interface LocationManager () <CLLocationManagerDelegate>
  11. @property (nonatomic, strong) CLLocationManager* locationManager;
  12. @end
  13. @implementation LocationManager
  14. + (LocationManager *)shareInstance
  15. {
  16. @synchronized(self)
  17. {
  18. // 实例对象只分配一次
  19. if(_instance == nil)
  20. {
  21. _instance = [[super allocWithZone:NULL] init];
  22. }
  23. }
  24. return _instance;
  25. }
  26. + (id)allocWithZone:(NSZone *)zone
  27. {
  28. return [self shareInstance];
  29. }
  30. - (id)copyWithZone:(NSZone *)zone
  31. {
  32. return self;
  33. }
  34. - (CLLocationManager *)locationManager {
  35. if (_locationManager == nil) {
  36. _locationManager = [[CLLocationManager alloc] init];
  37. _locationManager.delegate = self;
  38. _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
  39. }
  40. return _locationManager;
  41. }
  42. - (void)startUpdatingLocation
  43. {
  44. if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
  45. NSLog(@"requestWhenInUseAuthorization =======:");
  46. [self.locationManager requestWhenInUseAuthorization];
  47. }
  48. //开始定位,不断调用其代理方法
  49. [self.locationManager startUpdatingLocation];
  50. }
  51. - (void)stopUpdatingLocation {
  52. [self.locationManager stopUpdatingLocation];
  53. }
  54. - (void)locationManager:(CLLocationManager *)manager
  55. didUpdateLocations:(NSArray *)locations
  56. {
  57. // 1.获取用户位置的对象
  58. CLLocation *location = [locations lastObject];
  59. CLLocationCoordinate2D coordinate = location.coordinate;
  60. if ([self.delegate respondsToSelector: @selector(updateLocationWithCoordinate:)]) {
  61. [self.delegate updateLocationWithCoordinate: coordinate];
  62. }
  63. // 2.停止定位
  64. [manager stopUpdatingLocation];
  65. }
  66. @end