獲取用戶位置
Core Location框架提供了三種用於追蹤設備當前位置的服務,Core Location框架從內置的蜂窩,Wi-Fi或者GPS來獲取位置
如果程序必須使用位置服務
在程序的info.plist中添加UIRequiredDeviceCapabilities鍵,它是一個包含多個字符串的數組,然後添加location-services,gps字符串
1.The Standard Location Service
[plain]
- Listing 1-1 Starting the standard location service
- - (void)startStandardUpdates
- {
- // 創建location manager
- if (nil == locationManager)
- locationManager = [[CLLocationManager alloc] init];
-
- locationManager.delegate = self;
[plain]
- <span > // 設置獲取位置的精確度,越精確越耗電</span>
[plain]
- <span > locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
-
- // 設置距離過濾器,超過次距離就更新一次位置
- locationManager.distanceFilter = 500;
-
- [locationManager startUpdatingLocation];
- }</span>
使用location manager之前一般要檢查位置服務是否可用,
[plain]
- <span >+ (BOOL)locationServicesEnabled</span>
當位置信息更新時,會給location manager發送消息
2.Significant-Change Location Service
[plain]
- <span >- (void)startSignificantChangeUpdates
- {
- // Create the location manager if this object does not
- // already have one.
- if (nil == locationManager)
- locationManager = [[CLLocationManager alloc] init];
-
- locationManager.delegate = self;
- [locationManager startMonitoringSignificantLocationChanges];
- }</span>
可以叫醒在後台的程序
3.Region monitoring Service
使用之前調用CLLocationManager的regionMonitoringAvailable and regionMonitoringEnabled
[plain]
- <span >- (BOOL)registerRegionWithCircularOverlay:(MyCircle*)overlay andIdentifier:(NSString*)identifier
- {
- // Do not create regions if support is unavailable or disabled.
- if ( ![CLLocationManager regionMonitoringAvailable] ||
- ![CLLocationManager regionMonitoringEnabled] )
- return NO;
-
- // If the radius is too large, registration fails automatically,
- // so clamp the radius to the max value.
- CLLocationDegrees radius = overlay.radius;
- if (radius > self.locationManager.maximumRegionMonitoringDistance)
- radius = self.locationManager.maximumRegionMonitoringDistance;
-
- // Create the region and start monitoring it.
- CLRegion* region = [[CLRegion alloc] initCircularRegionWithCenter:overlay.coordinate
- radius:radius identifier:identifier];
- [self.locationManager startMonitoringForRegion:region
- desiredAccuracy:kCLLocationAccuracyHundredMeters];
-
- [region release];
- return YES;
- }</span>