IOS 定位(获取当前位置信息)

IOS 的定位已经不是很新鲜的了,定位共有三种方式,今天就其中的一种说一下,现在的版本中要多写上一句代码才可以完整的运行定位方法。此代码的意义是在第一次打开程序时提示用户是否允许该应用获取位置。 

在开始写代码之前我们需要加入CoreLocation.framework这个框架!然后再ViewController.h中包含头文件

#import <CoreLocation/CoreLocation.h>

#import <CoreLocation/CLLocationManagerDelegate.h>

再加上一个代理

<CLLocationManagerDelegate>

-(void)viewWillAppear:(BOOL)animated
{
    //开始定位
    [_locationManager requestWhenInUseAuthorization];        //定位前需提示是否定位
    [_locationManager startUpdatingLocation];
    
}

开始定位的方法写在这里只是为了打开程序就直接获取地理位置信息。

#pragma mark 实现位置更新
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currLocation = [locations lastObject];
    MYLog(@"纬度=%f  经度=%f  高度=%f",currLocation.coordinate.latitude,currLocation.coordinate.longitude,currLocation.altitude);

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             MYLog(@"%@",placemark.name);
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                 city = placemark.administrativeArea;
             }
             NSLog(@"city = %@", city);
             
         }
         else if (error == nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }
         else if (error != nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
     }];
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值