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.創(chuàng)建定位管理者
-(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.狀態(tài)監(jiān)聽
-(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.調(diào)用定位信息
-(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];
}