星空网 > 软件开发 > 操作系统

iOS开发日记49

今天博主有一个定位CLLocation的需求,遇到了一些困难点,在此和大家分享,希望能够共同进步.

使用定位功能,首先要导入框架,遵守CLLocationManagerDelegate协议,再创建位置管理器CLLocationManager

在iOS8.0后,定位功能需要在info.plist中加入NSLocationWhenInUseUsageDescription和NSLocationAlwaysUsageDescription这两个NSString类型字段,才能够使用定位功能

代码贴出来与大家共勉,各位看官自行研究

{

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

    _locationManager.delegate = self;

    if([CLLocationManager locationServicesEnabled] == NO) {

        

     //   NSLog(@"没有GPS服务");

        

    }

    //地理位置精确度

    _locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;

    //设置距离筛选器,double类型,只要距离变化多少,就调用委托代理

    self.locationManager.distanceFilter = kCLDistanceFilterNone; // meters

    [_locationManager requestWhenInUseAuthorization];// 前台定位

 

    [_locationManager startUpdatingLocation];

 

}

 

- (void)locationManager:(CLLocationManager *)manager

     didUpdateLocations:(NSArray *)locations

{

    NSLog(@"longitude = %f", ((CLLocation *)[locations

                                             lastObject]).coordinate.longitude);

    NSLog(@"latitude = %f", ((CLLocation *)[locations lastObject]).coordinate.latitude);

    

        CGFloat longTI=((CLLocation *)[locations

                                       lastObject]).coordinate.longitude;

    

        CGFloat latTI=((CLLocation *)[locations lastObject]).coordinate.latitude;

    

        //将经度显示到label上

        _longitudeLabel.text = [NSString stringWithFormat:@"%f",longTI];

        //将纬度现实到label上

        _latitudeLabel.text = [NSString stringWithFormat:@"%f",latTI];

    

    // 获取当前所在的城市名

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    //根据经纬度反向地理编译出地址信息

    [geocoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray *array, NSError *error)

     {

         if (array.count > 0)

         {

             CLPlacemark *placemark = [array objectAtIndex:0];

             

//             //将获得的所有信息显示到label上

//             self.location.text = placemark.name;

             //获取城市

             NSString *city = placemark.locality;

             if (!city) {

                 //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)

                 city = placemark.administrativeArea;

             }

            // NSLog(@"city = %@", city);

             _cityName=city;

         }

         else if (error == nil && [array count] == 0)

         {

           //  NSLog(@"No results were returned.");

         }

         else if (error != nil)

         {

            // NSLog(@"An error occurred = %@", error);

         }

 

     }];

    

    //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新

    [manager stopUpdatingLocation];

    

}

 




原标题:iOS开发日记49

关键词:IOS

IOS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流