美文网首页
ios开发 获取设备GPS信息

ios开发 获取设备GPS信息

作者: PengboGai | 来源:发表于2017-11-10 11:02 被阅读0次

    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];

    }

    有时候上面的都设置好了,但是还没有回调,有可能是因为不是在主线程里调用的,不能在静态方法里直接调用,因为有可能又开了一个线程来调用这个方法,那这样主线程就收不到回调了

    相关文章

      网友评论

          本文标题:ios开发 获取设备GPS信息

          本文链接:https://www.haomeiwen.com/subject/adxbmxtx.html