#import "ViewController.h"git
#import <MapKit/MapKit.h>數組
#import <CoreLocation/CoreLocation.h>app
// 獲取當前版本號ide
#define kCURRENTVERSION [[[UIDevice currentDevice] systemVersion] floatValue]atom
@interface ViewController ()<CLLocationManagerDelegate, UIAlertViewDelegate, UITextFieldDelegate>spa
@property (nonatomic, strong) CLLocationManager *locManager; // 獲取當前經緯度code
@property (nonatomic, strong) CLGeocoder *geocoder; // 經過經緯度轉換成地址orm
@property (strong, nonatomic) IBOutlet UILabel *longitudeLabel; // 經度事件
@property (strong, nonatomic) IBOutlet UILabel *latitudeLabel; // 緯度ci
@property (strong, nonatomic) IBOutlet UILabel *addressLabel; // 詳細地址
@property (strong, nonatomic) IBOutlet UILabel *stateLabel; // 省份
- (IBAction)getAction:(id)sender; // 獲取當前經緯度的按鈕
@property (strong, nonatomic) IBOutlet UITextField *addressTextField; // 輸入地址的textfield
- (IBAction)addressInput:(id)sender; // 根據地址轉換成經緯度按鈕
@end
@implementation ViewController
#pragma mark 實現懶加載
- (CLLocationManager *)locManager
{
if (_locManager == nil) {
self.locManager = [[CLLocationManager alloc] init];
self.locManager.delegate = self;
}
return _locManager;
}
- (CLGeocoder *)geocoder
{
if (_geocoder == nil) {
self.geocoder = [[CLGeocoder alloc] init];
}
return _geocoder;
}
#pragma mark 頁面消失的時候關閉定位
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// 關閉定位
[self.locManager stopUpdatingLocation];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化設置
self.longitudeLabel.textAlignment = NSTextAlignmentCenter;
self.latitudeLabel.textAlignment = NSTextAlignmentCenter;
self.addressLabel.numberOfLines = 0;
self.addressTextField.delegate = self;
}
- (void)requestWhenInUseAuthorization
{
self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locManager.distanceFilter = 10;
#pragma mark ------------如下二選一---------------
[self.locManager requestWhenInUseAuthorization];//當程序運行的時候獲取定位權限
//[self.locManager requestAlwaysAuthorization]; // 程序一直獲取定位權限
}
//協議中的方法,做用是每當位置發生更新時會調用的委託方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
// 獲取數組第一個元素
CLLocation *loc = [locations firstObject];
// 獲取經度
self.longitudeLabel.text = [NSString stringWithFormat:@"%f", loc.coordinate.longitude];
// 獲取緯度
self.latitudeLabel.text = [NSString stringWithFormat:@"%f", loc.coordinate.latitude];
// 將經緯度轉換成地址
[self.geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
// 判斷數組是否爲空
if (placemarks.count > 0)
{
// 數組不爲空
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSDictionary *dic = placemark.addressDictionary;
// 轉換成詳細地址
[self getAddress:dic];
//獲取城市
NSString *city = placemark.locality;
if (!city) {
//四大直轄市的城市信息沒法經過locality得到,只能經過獲取省份的方法來得到(若是city爲空,則可知爲直轄市)
city = placemark.administrativeArea;
}
// 將省份顯示
self.stateLabel.text = city;
}
// 地址獲取失敗
else if (error == nil && [placemarks count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
[self.locManager stopUpdatingLocation];
}
#pragma mark 獲取當前詳細地址
- (void) getAddress:(NSDictionary *) addressDic
{
//NSString *state=[addressDic objectForKey:@"State"]; // 省份
NSString *city=[addressDic objectForKey:@"City"]; // 城市
NSString *subLocality=[addressDic objectForKey:@"SubLocality"]; // 區
NSString *street=[addressDic objectForKey:@"Street"]; // 街道
NSString *address = [[city stringByAppendingString:subLocality] stringByAppendingString:street]; // 拼接地址
self.addressLabel.text = address; // 顯示地址
}
//當位置獲取或更新失敗會調用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSString *errorMsg = nil; // 做爲提示框的信息
if ([error code] == kCLErrorDenied) {
errorMsg = @"訪問被拒絕,請容許應用獲取定位權限";
}
if ([error code] == kCLErrorLocationUnknown) {
errorMsg = @"獲取位置信息失敗";
}
// 建立提示框
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"定位失敗" message:errorMsg preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確認" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
// 當應用無權限獲取位置信息 從新獲取
[self requestWhenInUseAuthorization];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark 定位失敗提示
- (void) showAlert:(NSString *) notice
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"定位失敗" message:notice preferredStyle:(UIAlertControllerStyleAlert)];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確認" style:(UIAlertActionStyleDefault) handler:nil];
[alertController addAction:okAction];
//[self.view addSubview:alertController.view];
[self presentViewController:alertController animated:YES completion:^{
}];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark 獲取當前經緯度 button點擊事件
- (IBAction)getAction:(id)sender {
// 判斷手機定位是否打開
if (kCURRENTVERSION >= 8.0) {
if ([CLLocationManager locationServicesEnabled]) {
[self requestWhenInUseAuthorization];
// 設置距離篩選器distanceFilter,沒有篩選器設置
self.locManager.distanceFilter = kCLDistanceFilterNone;
// 精確度 當前選擇最精確
self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locManager startUpdatingLocation];
}
else
{
[self showAlert:@"手機定位未開啓"];
}
}
}
#pragma mark 獲取地址的經緯度 button點擊事件
- (IBAction)addressInput:(id)sender {
NSString *address = self.addressTextField.text;
// 判斷地址是否爲空
if (address.length == 0) {
[self showAlert:@"地址不能爲空"];
return;
}
// 地址不爲空 轉換成 CLGeocoder 類型
[self.geocoder geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (error || placemarks.count == 0) {
[self showAlert:@"你輸入的地址沒找到,可能在火星上"];
}
else{
// 取第一個元素
CLPlacemark *firstPlacemark = [placemarks firstObject];
// 獲取第一個元素的經緯度
CLLocationCoordinate2D coordinate = firstPlacemark.location.coordinate;
self.longitudeLabel.text = [NSString stringWithFormat:@"%f", coordinate.longitude];
self.latitudeLabel.text = [NSString stringWithFormat:@"%f", coordinate.latitude];
}
}];
}
// 回收鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
@end