今天无聊玩了一下定位,发现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];
}