您的位置:首页 > 移动开发 > IOS开发

iOS 自带的定位系统 (设置注意事项)

2016-04-21 12:02 519 查看
最近在ios8.0使用CLLocationManager定位服务,发现老不能定位,查看设置菜单中的项也是处于未知状态.想起之前都有一个弹出框提示用户是否允许定位,这次一直没有出现了.原来ios8.0下的定位服务需要申请授权了. 具体代码如下:

if ([CLLocationManager locationServicesEnabled]) {

self.locationManager = [[CLLocationManager alloc] init];

_locationManager.delegate = self;

_locationManager.desiredAccuracy = kCLLocationAccuracyBest; //控制定位精度,越高耗电量越大。

_locationManager.distanceFilter = 100; //控制定位服务更新频率。单位是“米”

[_locationManager startUpdatingLocation];

//在ios 8.0下要授权

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

[_locationManager requestWhenInUseAuthorization]; //调用了这句,就会弹出允许框了.

}

注意:

在Info.plist文件还要加上NSLocationWhenInUseUsageDescription这个key,Value可以为空,


#pragma mark - CLLocationManagerDelegate

(void)locationManager:(CLLocationManager )manager didUpdateLocations:(NSArray )locations {

CLLocation * currLocation = [locations lastObject];

NSLog(@”%@”,[NSString stringWithFormat:@”%.3f”,currLocation.coordinate.latitude]);

NSLog(@”%@”,[NSString stringWithFormat:@”%.3f”,currLocation.coordinate.longitude]);

}

模拟区需要设置初始位置(不然无法使用),看选的是 custom Location 还是 Apple 选项 (具体不太明白)

在模拟器的菜单中




//
//  KCMainViewController.m
//  CoreLocation
//
//  Created by Kenshin Cui on 14-03-27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface KCMainViewController ()<CLLocationManagerDelegate>{

CLLocationManager *_locationManager;
}

@end

@implementation KCMainViewController

- (void)viewDidLoad {
[super viewDidLoad];

//定位管理器
_locationManager=[[CLLocationManager alloc]init];

if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"定位服务当前可能尚未打开,请设置打开!");
return;
}

//如果没有授权则请求用户授权
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
[_locationManager requestWhenInUseAuthorization];
}else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
//设置代理
_locationManager.delegate=self;
//设置定位精度
_locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//定位频率,每隔多少米定位一次
CLLocationDistance distance=10.0;//十米定位一次
_locationManager.distanceFilter=distance;
//启动跟踪定位
[_locationManager startUpdatingLocation];
}
}

#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法,每次位置发生变化即会执行(只要定位到相应位置)
//可以通过模拟器设置一个虚拟位置,否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *location=[locations firstObject];//取出第一个位置
CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
//如果不需要实时定位,使用完即使关闭定位服务
[_locationManager stopUpdatingLocation];
}

@end


可配合 CLGeocoder *_geocoder; 使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: