#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> #import <MapKit/MapKit.h> @interface ANNViewController : UIViewController <CLLocationManagerDelegate> @end #import "ANNViewController.h" @interface ANNViewController () @property (strong, nonatomic) IBOutlet UILabel *longitude; @property (strong, nonatomic) IBOutlet UILabel *latitude; @property (strong, nonatomic) IBOutlet UILabel *location; @property (strong, nonatomic) CLLocationManager *locationManager; @end @implementation ANNViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor whiteColor]; //ios 8後 //在Info.plist中加入兩個缺省沒有的字段 //NSLocationAlwaysUsageDescription //NSLocationWhenInUseUsageDescription //建立CLLocationManager對象 self.locationManager = [[CLLocationManager alloc] init]; //設置代理爲本身 if ([CLLocationManager locationServicesEnabled]) { NSLog( @"Starting CLLocationManager" ); self.locationManager.delegate = self; [self.locationManager requestAlwaysAuthorization]; self.locationManager.distanceFilter = 200; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; [self.locationManager startUpdatingLocation]; } else { NSLog( @"Cannot Starting CLLocationManager" ); /*self.locationManager.delegate = self; self.locationManager.distanceFilter = 200; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [self.locationManager startUpdatingLocation];*/ } } - (IBAction)locationButton:(UIButton *)sender { [self.locationManager startUpdatingLocation]; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { //將經度顯示到label上 self.longitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.longitude]; //將緯度現實到label上 self.latitude.text = [NSString stringWithFormat:@"%lf", newLocation.coordinate.latitude]; // 獲取當前所在的城市名 CLGeocoder *geocoder = [[CLGeocoder alloc] init]; //根據經緯度反向地理編譯出地址信息 [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error) { if (array.count > 0) { CLPlacemark *placemark = [array objectAtIndex:0]; //將得到的全部信息顯示到label上 self.location.text = 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); } }]; //系統會一直更新數據,直到選擇中止更新,由於咱們只須要得到一次經緯度便可,因此獲取以後就中止更新 // [manager stopUpdatingLocation]; } -(void)locationManager:(CLLocationManager *)manager didFailWithError:(nonnull NSError *)error { NSLog(@"%@",error); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end