歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iPhone獲取當前位置(CoreLocation的一些簡單使用)

iPhone獲取當前位置(CoreLocation的一些簡單使用)

日期:2017/3/1 10:36:08   编辑:Linux編程

獲取用戶位置

Core Location框架提供了三種用於追蹤設備當前位置的服務,Core Location框架從內置的蜂窩,Wi-Fi或者GPS來獲取位置

  • The significant-change location

    service 提供了低耗電的方法來獲取當前位置,當前位置改變時會發出通知
  • The standard location service 提供了一種可設置的方法來獲取當前位置

  • Region monitoring 監視特定地區的跨越

如果程序必須使用位置服務 在程序的info.plist中添加UIRequiredDeviceCapabilities鍵,它是一個包含多個字符串的數組,然後添加location-services,gps字符串

1.The Standard Location Service 
[plain]
  1. Listing 1-1 Starting the standard location service
  2. - (void)startStandardUpdates
  3. {
  4. // 創建location manager
  5. if (nil == locationManager)
  6. locationManager = [[CLLocationManager alloc] init];
  7. locationManager.delegate = self;
[plain]
  1. <span >  // 設置獲取位置的精確度,越精確越耗電</span>
[plain]
  1. <span > locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
  2. // 設置距離過濾器,超過次距離就更新一次位置
  3. locationManager.distanceFilter = 500;
  4. [locationManager startUpdatingLocation];
  5. }</span>
使用location manager之前一般要檢查位置服務是否可用, [plain]
  1. <span >+ (BOOL)locationServicesEnabled</span>

當位置信息更新時,會給location manager發送消息

2.Significant-Change Location Service

[plain]
  1. <span >- (void)startSignificantChangeUpdates
  2. {
  3. // Create the location manager if this object does not
  4. // already have one.
  5. if (nil == locationManager)
  6. locationManager = [[CLLocationManager alloc] init];
  7. locationManager.delegate = self;
  8. [locationManager startMonitoringSignificantLocationChanges];
  9. }</span>

可以叫醒在後台的程序


3.Region monitoring Service 使用之前調用CLLocationManager的regionMonitoringAvailable and regionMonitoringEnabled
[plain]
  1. <span >- (BOOL)registerRegionWithCircularOverlay:(MyCircle*)overlay andIdentifier:(NSString*)identifier
  2. {
  3. // Do not create regions if support is unavailable or disabled.
  4. if ( ![CLLocationManager regionMonitoringAvailable] ||
  5. ![CLLocationManager regionMonitoringEnabled] )
  6. return NO;
  7. // If the radius is too large, registration fails automatically,
  8. // so clamp the radius to the max value.
  9. CLLocationDegrees radius = overlay.radius;
  10. if (radius > self.locationManager.maximumRegionMonitoringDistance)
  11. radius = self.locationManager.maximumRegionMonitoringDistance;
  12. // Create the region and start monitoring it.
  13. CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:overlay.coordinate
  14. radius:radius identifier:identifier];
  15. [self.locationManager startMonitoringForRegion:region
  16. desiredAccuracy:kCLLocationAccuracyHundredMeters];
  17. [region release];
  18. return YES;
  19. }</span>
Copyright © Linux教程網 All Rights Reserved