首先要在plist文件里添加兩個鍵值對,向用戶請求位置服務(wù)時會顯示在這里設(shè)置的值的內(nèi)容仿耽。
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
導(dǎo)入頭文件
#import <CoreLocation/CoreLocation.h>
把CLLocationManager設(shè)置為屬性项贺。
這里有一個坑點峭判,如果不設(shè)置為屬性林螃,軟件開啟時提示定位的提示出現(xiàn)一瞬間就消失了治宣。
被這個坑了一會兒砌滞,最后才發(fā)現(xiàn)是因為沒有設(shè)置成屬性的緣故坏怪。
@interface HomeViewController ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
@implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self startLocation];
// Do any additional setup after loading the view.
}
//開始定位
- (void)startLocation {
if ([CLLocationManager locationServicesEnabled]) {
// CLog(@"--------開始定位");
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
//控制定位精度,越高耗電量越
self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
// 總是授權(quán)
[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) {
CLog(@"訪問被拒絕");
}
if ([error code] == kCLErrorLocationUnknown) {
CLog(@"無法獲取位置信息");
}
}
//定位代理經(jīng)緯度回調(diào)
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *newLocation = locations[0];
// 獲取當(dāng)前所在的城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//根據(jù)經(jīng)緯度反向地理編譯出地址信息
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
if (array.count > 0){
CLPlacemark *placemark = [array objectAtIndex:0];
//獲取城市
NSString *city = placemark.locality;
if (!city) {
//四大直轄市的城市信息無法通過locality獲得打掘,只能通過獲取省份的方法來獲得(如果city為空尊蚁,則可知為直轄市)
city = placemark.administrativeArea;
}
NSLog(@"city = %@", city);
[self httpGetWeather:city];
}
else if (error == nil && [array count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
//系統(tǒng)會一直更新數(shù)據(jù)侣夷,直到選擇停止更新,因為我們只需要獲得一次經(jīng)緯度即可琴锭,所以獲取之后就停止更新
[manager stopUpdatingLocation];
}