地图_SDK

ios 定位总结

2016-01-15  本文已影响1327人  Roger_单

我们是这样实现定位的:

首先我们要实例化一个CLLocationManager的对象,然后来进行设置。

如果是IOS9 设置是否允许后台定位 >=9

如果是IOS8 设置使用中才开始定位或者始终在后台定位 >=8

实现对象的委托方法,之后调用startUpdatingLocation来实现开始定位

如果定位失败 就调用定位失败的委托方法

Errorcode 可以获得如何失败原因

如果定位成功 将会走定位成功的委托方法New Location参数

我们可以成功的定位出经纬度,转码通过CLGEOCode转换成文字,显示到对应的位置。
Info.plist 里 加 NSLocationWhenInUseUsageDescription (Boolean YES)
NSLocationAlwaysUsageDescription 是否总在后台定位
NSLocationWhenInUseUsageDescription 使用时定位(inpo.plist )

大连坐标 38.849648 121.517977(先在Xcode Debug 然后SimulateLocation 再随便选个,模拟器上Debug 然后Location 再点Custom...)

-(void)viewWillAppear:(BOOL)animated{
    [self getsearchSupermarketList];
    [super viewWillAppear:animated];
    [self initlocationManager];//定位 走这个方法

@interface SuperMarketViewController () <CLLocationManagerDelegate>
>

#pragma -mark Location
// 定位
-(void)initlocationManager{
     _locationManager=[[CLLocationManager alloc] init];
    _locationManager.delegate=self;
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    _locationManager.distanceFilter=10;
    // 5.iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
       // _locationManager.allowsBackgroundLocationUpdates = YES;
    }
    if (IOS_VERSION>=8) {
        [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8定位需要)
    }
    [_locationManager startUpdatingLocation];//开启定位
}
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations{
       CLLocation *currLocation=[locations lastObject];
    NSLog(@"la---%f, lo---%f",currLocation.coordinate.latitude,currLocation.coordinate.longitude);
     // 使用CLGeocoder的做法,其实是因为ios5开始,iphone推荐的做法。而MKReverseGeocoder在ios5之后,就不再推荐使用了,因为这个类需要实现两个委托方法。而使用CLGeocodre,则可以使用直接的方法。
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray* placemarks,NSError *error) {
          if (placemarks.count >0   ) {
            // 自动定位获取城市等信息
            CLPlacemark * plmark = [placemarks objectAtIndex:0];
            NSLog(@"%@", plmark.name); //显示所有地址
            _label.text = plmark.name; //给label负值
        }
    }];
    }
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
      if ([error code]==kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code]==kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
上一篇 下一篇

猜你喜欢

热点阅读