1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//
// LocationHelper.m
// RealEstateManagement
//
// Created by Javen on 2016/10/10.
// Copyright © 2016年 上海勾芒信息科技. All rights reserved.
//
#import "LocationHelper.h"
#import <CoreLocation/CoreLocation.h>
@interface LocationHelper ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
@implementation LocationHelper
+ (LocationHelper *)shareInstance {
static LocationHelper *helper = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
helper = [[LocationHelper alloc] init];
});
return helper;
}
- (void)getCityNameSuccess:(locationBlock)success failed:(locationBlock)failed {
self.blockSuccess = success;
self.blockFailed = failed;
[self startLocation];
}
#pragma mark - 定位方法
//开始定位
- (void)startLocation {
if ([CLLocationManager locationServicesEnabled]) {
// CLog(@"--------开始定位");
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
//控制定位精度,越高耗电量越
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// 总是授权
[self.locationManager requestAlwaysAuthorization];
self.locationManager.distanceFilter = 10.0f;
[self.locationManager requestAlwaysAuthorization];
[self.locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if ([error code] == kCLErrorDenied) {
if (self.blockFailed) {
self.blockFailed(@"访问被拒绝");
}
}
if ([error code] == kCLErrorLocationUnknown) {
if (self.blockFailed) {
self.blockFailed(@"无法获取位置信息");
}
}
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *newLocation = locations[0];
// 获取当前所在的城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//根据经纬度反向地理编译出地址信息
WS(weakSelf);
[geocoder reverseGeocodeLocation:newLocation
completionHandler:^(NSArray *array, NSError *error) {
if (array.count > 0) {
CLPlacemark *placemark = [array objectAtIndex:0];
//获取城市
NSString *city = placemark.locality;
// NSString *zipCode = placemark.postalCode;
if (!city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city = placemark.administrativeArea;
}
weakSelf.blockSuccess(city);
} else if (error == nil && [array count] == 0) {
NSLog(@"No results were returned.");
} else if (error != nil) {
NSLog(@"An error occurred = %@", error);
}
}];
//系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
[manager stopUpdatingLocation];
}
@end