iOS 自带定位功能CoreLocation

定位功能的实现

苹果自带定位功能的实现代码如下:
首先要导入coreLocation.framework库,然后导入

//
//  AppDelegate.m
//  定位
//
//  Copyright © 2016年 Wss. All rights reserved.
//

#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>

@interface AppDelegate ()<CLLocationManagerDelegate>
@property(nonatomic, strong) CLLocationManager *locationManager;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    //定位
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;  //系统自动帮你选择定位的最佳方式
    self.locationManager.distanceFilter = 1;   //1米定位一次

    if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager startUpdatingLocation];


    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位服务当前可能尚未打开,请设置打开!" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
        [alter show];
    }

    return YES;
}
#pragma mark - location manager delegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    //取出位置
    CLLocation *location = [locations lastObject];

    // 反向地理编码,取出具体中文位置,保存起来,方便在需要显示的地方赋值
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error &&[placemarks count]>0) {
            NSDictionary *dict = [[placemarks objectAtIndex:0] addressDictionary];
            NSLog(@"---------adderss:%@",dict);
            NSLog(@"city:%@-country:%@-countryCCode:%@-fromattedAddressLines:%@-name:%@-state:%@-sublocality:%@",dict[@"City"],dict[@"Country"],dict[@"CountryCode"],dict[@"FormattedAddressLines"][0],dict[@"Name"],dict[@"State"],dict[@"SubLocality"]);
            [[NSUserDefaults standardUserDefaults]setObject:dict forKey:@"adderss"];
        }else
        {
            NSLog(@"error:%@",error);
        }
    }];

    //如定位完成后,不需要再实时更新,就关掉定位服务
    [self.locationManager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"---------------error:%@",error);
}

@end

在需要的界面赋值

NSDictionary *dict = [[NSUserDefaults standardUserDefaults]objectForKey:@"adderss"];
    UILabel *locationDes = [[UILabel alloc]initWithFrame:CGRectMake(20, 100, self.view.frame.size.width-40, 60)];
    locationDes.numberOfLines = 0;
    locationDes.layer.borderColor =  [UIColor groupTableViewBackgroundColor].CGColor;
    locationDes.layer.borderWidth = 1.0;
    [locationDes.layer setMasksToBounds:YES];
    [locationDes.layer setCornerRadius:8.0];
    locationDes.text = [NSString stringWithFormat:@"位置:%@",dict[@"Name"]];
    [self.view addSubview:locationDes];

地理编码,获取经纬度


CLGeocoder *geocoder = [[CLGeocoder alloc]init];
     [geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
         //如果有错误信息,或者是数组中获取的地名元素数量为0,那么说明没有找到
         if (error || placemarks.count==0) {
            self.detailAddressLabel.text=@"你输入的地址没找到,可能在月球上";
        }else   //  编码成功,找到了具体的位置信息
         {
            //打印查看找到的所有的位置信息
                 /*
                     name:名称
                    locality:城市
                    country:国家
                     postalCode:邮政编码
                  */

            //取出获取的地理信息数组中的第一个显示在界面上
            CLPlacemark *firstPlacemark=[placemarks firstObject];

            //纬度
            CLLocationDegrees latitude=firstPlacemark.location.coordinate.latitude;
             //经度
              CLLocationDegrees longitude=firstPlacemark.location.coordinate.longitude;

        }
     }];

反向地理编码,由经纬度获取中文地址

 CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error &&[placemarks count]>0) {
            NSDictionary *dict = [[placemarks objectAtIndex:0] addressDictionary];
            NSLog(@"---------adderss:%@",dict);
            NSLog(@"city:%@-country:%@-countryCCode:%@-fromattedAddressLines:%@-name:%@-state:%@-sublocality:%@",dict[@"City"],dict[@"Country"],dict[@"CountryCode"],dict[@"FormattedAddressLines"][0],dict[@"Name"],dict[@"State"],dict[@"SubLocality"]);
            [[NSUserDefaults standardUserDefaults]setObject:dict forKey:@"adderss"];
        }else
        {
            NSLog(@"error:%@",error);
        }
    }];

在用真机测试的时候一定要记得在真机的设置里开启定位服务!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值