1.这只是导航栏上面的运用
在这机上会自动获取当前的城市 //1.挂代理 CLLocationManagerDelegate
导入#import <CoreLocation/CoreLocation.h>
//两个属性
NSString *Citystring;// 城市名
@property(nonatomic,strong) CLLocationManager *locationManger;
@property(nonatomic,strong) CLGeocoder *geocoder;
#pragma mark 用户对地理位置的确定
-(CLGeocoder *)geocoder
{
if (!_geocoder) {
_geocoder = [[CLGeocoder alloc]init];
}
return _geocoder;
}
//1.创建定位管理者
-(CLLocationManager *)locationManger
{
if (!_locationManger) {
_locationManger = [[CLLocationManager alloc]init];
}
return _locationManger;
}
#pragma mark - 定位
-(void)CityLoation
{
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"定位" style:UIBarButtonItemStylePlain target:self action:@selector(clickStatee)];
//2.挂代理
self.locationManger.delegate = self;
//3.对设备进行判断,因为安全要求高了(记得在Info.plist里面进行配置requestAlwaysAuthorization点击进去配置)
if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) {
NSLog(@"这是iOS8设备");
[self.locationManger requestAlwaysAuthorization];
}else
{
NSLog(@"不是iOS8的设备");
}
}
//4.状态监听
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
if (status == kCLAuthorizationStatusNotDetermined) {
DFTLog(@"等待授权");
}else if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse )
{
DFTLog(@"授权成功");
//始终
// self.locationManger.desiredAccuracy = kCLLocationAccuracyBest;
// self.locationManger.distanceFilter = 10.0f;
[self.locationManger startUpdatingLocation];
}
else
{
DFTLog(@"定位失败");
}
}
//5.调用定位信息
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *location = [locations lastObject];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
for (CLPlacemark *placemark in placemarks) {
//接收定位出来的地理位置
Citystring = placemark.locality;
DFTLog(@"=====%@",Citystring);
self.navigationItem.leftBarButtonItem.title = Citystring;
}
}];
[self.locationManger stopUpdatingLocation];(定位成功我们要关闭定位,减少性能的消耗)
}
3.点击上面的定位,我们可以自己获取位置
这时我们需要导入一个封装好的类 城市选择框架
#import "CityViewController.h"
点击上面的定位选择地理位置
#pragma mark - 城市选择
-(void)clickStatee
{
CityViewController *controller = [[CityViewController alloc] init];
这个赋值是当前这个控制器的位置带到这个框架里面去,显示当前的位置
controller.currentCityString = Citystring;
//block传值(把值带出来)
controller.selectString = ^(NSString *string){
self.navigationItem.leftBarButtonItem.title = string;
};
[self presentViewController:controller animated:YES completion:nil];
}
网友评论