#import <CoreLocation/CoreLocation.h>
.h
@property (nonatomic,strong) CLLocationManager * manager;
@property (nonatomic,assign) BOOL isLocationed;
.m
-(CLLocationManager *)manager{
if (!_manager) {
_manager = [[CLLocationManager alloc]init];
_manager.delegate = self;
_manager.desiredAccuracy = kCLLocationAccuracyBest;
}
return _manager;
}
#pragma mark
#pragma mark - 判断手机是否开启定位功能 然后开始定位
- (void)findLocationCity{
if ([CLLocationManager locationServicesEnabled]) {
if ([self.manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
// NSLog(@"requestWhenInUseAuthorization");
[self.manager requestWhenInUseAuthorization];
}
[self.manager startUpdatingLocation];
// NSLog(@"start GPS");
}else{
NSLog(@"提醒用户:定位服务未开启,可在设置中进行修改....");
}
}
#pragma mark
#pragma mark - 获取 GPS 经度和纬度
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray<CLLocation *> *)locations{
if (!_isLocationed) {
CLLocation * location1 = [locations lastObject];
CLLocationCoordinate2D coordinate = location1.coordinate;
CLGeocoder * geocoder = [[CLGeocoder alloc]init];
CLLocation * location = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (placemarks.count > 0) {
CLPlacemark * placemark = [placemarks objectAtIndex:0];
NSString * city = placemark.locality;
if (!city) {
city = placemark.administrativeArea;
}
UIAlertController * ac = [UIAlertController alertControllerWithTitle:@"切换当前城市:" message:city preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * aa = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[WeatherView_Model weatherWithCurrentCity:city finishBlock:^(WeatherView_Model *weatherModel) {
self.weather_View.weatherModel = weatherModel;
} errorBlock:^{
}];
}];
[ac addAction:aa];
UIAlertAction * aa2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[ac addAction:aa2];
[self presentViewController:ac animated:YES completion:nil];
}else if (error == nil && placemarks.count == 0){
NSLog(@"No results were returned.");
}else if (error != nil){
NSLog(@"An error occurred = %@", error);
}
}];
self.isLocationed = YES;
}
[self.manager stopUpdatingLocation];
}
#pragma mark
#pragma mark - 定位失败返回
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
if (error.code == kCLErrorDenied) {
NSLog(@"Error : %@",error);
}
}
仅供学习 参考
网友评论