1、在Info.plist文件中添加如下配置:
(1)NSLocationAlwaysUsageDescription (value 就是你要显示的提示用户获取gps)
(2)NSLocationWhenInUseUsageDescription (value 就是你要显示的提示用户获取gps)
2.引入CoreLocation.framework
#import < CoreLocation/CoreLocation.h >
让APPcontroller 继承接口 CLLocationManagerDelegate
AppController :NSObject < UIAccelerometerDelegate,UIAlertViewDelegate,UITextFieldDelegate,UIApplicationDelegate,WXApiDelegate,CLLocationManagerDelegate >
3.添加全局变量
@property(nonatomic,strong)CLLocationManager*locationManager;
4.在didFinishLaunchingWithOptions方法中调用initGPS, 然后就可以在回调中获取到信息了(获取失败则会调用失败回调);
值得注意的是 在iOS8 以后必须加上:
[locationmanager requestWhenInUseAuthorization];(在使用时获取gps)
或者[locationmanager requestAlwaysAuthorization];(无论是否在使用都获取gps)
- (void) initGps{
locationmanager= [[CLLocationManageralloc]init];
//设置精度
/*
kCLLocationAccuracyBest
kCLLocationAccuracyNearestTenMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyHundredMeters
kCLLocationAccuracyKilometer
kCLLocationAccuracyThreeKilometers
*/
//设置定位的精度
[locationmanager setDesiredAccuracy:kCLLocationAccuracyBest];
//实现协议
locationmanager.delegate=self;
[locationmanager requestWhenInUseAuthorization];
NSLog(@"开始定位");
//开始定位
[locationmanager startUpdatingLocation];
}
//获取定位成功回调
- (void)locationManager:(CLLocationManager*)manager
didUpdateToLocation:(CLLocation*)newLocation
fromLocation:(CLLocation*)oldLocation
{
NSLog(@"hello");
//打印出精度和纬度
CLLocationCoordinate2Dcoordinate = newLocation.coordinate;
NSLog(@"输出当前的精度和纬度");
NSLog(@"精度:%f 纬度:%f",coordinate.latitude,coordinate.longitude);
//停止定位
//[locationmanager stopUpdatingLocation];
//计算两个位置的距离
floatdistance = [newLocationdistanceFromLocation:oldLocation];
NSLog(@" 距离 %f",distance);
}
//获取gps失败回调
- (void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error
{
NSLog(@"获取GPS失败!");
if([errorcode] ==kCLErrorDenied)
{
//访问被拒绝
}
if([errorcode] ==kCLErrorLocationUnknown) {
//无法获取位置信息
}
}
//停止获取GPS
- (void)stopUpdateGPS
{
[locationmanagerstopUpdatingLocation];
}