今天下午動手用了IOS自帶的定位,結果在網上看了不少教程,也將示例代碼直接運行,但就是一直沒法獲取位置,代碼以下:html
首先導入CoreLocation.framework,而後再引入頭文件#import java
定義屬性ios
1
|
@property
(nonatomic , strong)CLLocationManager *locationManager;
|
而後使用代理 CLLocationManagerDelegateiphone
- (void)locate{ // 判判定位操做是否被容許 if([CLLocationManager locationServicesEnabled]) { //定位初始化 _locationManager=[[CLLocationManager alloc] init]; _locationManager.delegate=self; _locationManager.desiredAccuracy=kCLLocationAccuracyBest; _locationManager.distanceFilter=10; [_locationManager startUpdatingLocation];//開啓定位 }else { //提示用戶沒法進行定位操做 UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@提示 message:@定位不成功 ,請確認開啓定位 delegate:nil cancelButtonTitle:@取消 otherButtonTitles:@肯定, nil]; [alertView show]; } // 開始定位 [_locationManager startUpdatingLocation]; } #pragma mark - CoreLocation Delegate -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { //此處locations存儲了持續更新的位置座標值,取最後一個值爲最新位置,若是不想讓其持續更新位置,則在此方法中獲取到一個值以後讓locationManager stopUpdatingLocation CLLocation *currentLocation = [locations lastObject]; // 獲取當前所在的城市名 CLGeocoder *geocoder = [[CLGeocoder alloc] init]; //根據經緯度反向地理編譯出地址信息 [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error) { if (array.count > 0) { CLPlacemark *placemark = [array objectAtIndex:0]; //NSLog(@%@,placemark.name);//具體位置 //獲取城市 NSString *city = placemark.locality; if (!city) { //四大直轄市的城市信息沒法經過locality得到,只能經過獲取省份的方法來得到(若是city爲空,則可知爲直轄市) city = placemark.administrativeArea; } cityName = city; NSLog(@定位完成:%@,cityName); //系統會一直更新數據,直到選擇中止更新,由於咱們只須要得到一次經緯度便可,因此獲取以後就中止更新 [manager stopUpdatingLocation]; }else if (error == nil && [array count] == 0) { NSLog(@No results were returned.); }else if (error != nil) { NSLog(@An error occurred = %@, error); } }]; }
在viewDidLoad中調用了locate以後一直沒有數據返回,代理也不執行,在網上找了不少教程,代碼大多大同小異,可是結果都是不理想,偶然之間看到ios8的定位和低版本的不一樣,個人手機恰好是ios8,便點開那個博客去看看,博客請點此進入函數
如下爲該博客摘要:atom
在iOS8之前的版本中,咱們使用CLLocationManager定位是沒有問題的,最近在iOS8系統中卻沒法定位了。。。。這是一大問題啊!spa
iOS8中使用CoreLocation定位代理
一、在使用CoreLocation前須要調用以下函數【iOS8專用】:
iOS8對定位進行了一些修改,其中包括定位受權的方法,CLLocationManager增長了下面的兩個方法:
(1)始終容許訪問位置信息code
1
|
- (
void
)requestAlwaysAuthorization;
|
(2)使用應用程序期間容許訪問位置數據htm
1
|
- (
void
)requestWhenInUseAuthorization;
|
示例以下
locationManager=[[CLLocationManager alloc] init]; locationManager.delegate=self; locationManager.desiredAccuracy=kCLLocationAccuracyBest; locationManager.distanceFilter=10; if (iOSVersion>=8) { [locationManager requestWhenInUseAuthorization];//使用程序其間容許訪問位置數據(iOS8定位須要) } [locationManager startUpdatingLocation];//開啓定位
二、在Info.plist文件中添加以下配置:(1)NSLocationAlwaysUsageDescription(2)NSLocationWhenInUseUsageDescription