今天無聊玩了一下定位,發現iOS8需要獲取用戶允許才能使用定位這茬給忘了,寫點東西來記錄一下。
先修改一下自己的info.plist文件,添加兩行:
key:NSLocationWhenInUseUsageDescription
value:我們需要你的地理位置獲取周邊信息
key:NSLocationAlwaysUsageDescription
value:我們需要你的地理位置獲取周邊信息
判斷定位功能是否有效(模擬器|真機):
if ([CLLocationManager locationServicesEnabled])
{
NSLog(@"begin test location");
NSLog(@"manager: %@", self.locationManager);
}
else
{
NSLog(@"no Support");
}
初始化CLLocationManager:
- (CLLocationManager *)locationManager
{
if (_locationManager == nil)
{
_locationManager = [[CLLocationManager alloc]init];
[_locationManager setDelegate:self];
_locationManager.distanceFilter = kCLLocationAccuracyBest;
_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
[_locationManager requestAlwaysAuthorization];
[_locationManager startUpdatingLocation];
}
return _locationManager;
}
前台運行:
_locationManager.distanceFilter = kCLLocationAccuracyBest;
_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
[self startLocation];
后台運行:
_locationManager.distanceFilter = kCLLocationAccuracyKilometer;
_locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
self.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(startLocation) userInfo:nil repeats:YES];
手動強制運行定位:
- (void)startLocation
{
[_locationManager stopUpdatingLocation];
[_locationManager startUpdatingLocation];
}