在IOS8更新之後之前的方法CLLocationManagerDelegate不調用didUpdateLocationsgit
iOS8修改了位置設置裏的內容,增長了一套狀態(使用中可用/一般可用),因此之前的CLLcationManage的註冊後,
Delegate接口不響應了,研究了一上午終於能夠用了app
說一下個人心得atom
(1)添加corelocation.frameworkspa
(2)在Info.plist中加入兩個缺省沒有的字段代理
NSLocationAlwaysUsageDescriptionrest
NSLocationWhenInUseUsageDescriptioncode
(3)導入頭文件orm
#import <CoreLocation/CoreLocation.h>blog
#import <CoreLocation/CLLocationManagerDelegate.h>接口
@interface PersonViewController : UIViewController<CLLocationManagerDelegate>{ CLLocationManager* locationManager; } @property (strong, nonatomic) CLLocationManager* locationManager; @end
(4)實例化並完成代理方法
-(void)startLocation{ [self.locationManager requestAlwaysAuthorization]; if ([CLLocationManager locationServicesEnabled]&&[CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) { self.locationManager = [[CLLocationManager alloc] init]; [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; self.locationManager.delegate = self; if (__IPHONE_8_0) { NSLog(@"here"); self.locationManager.distanceFilter = kCLDistanceFilterNone; [self.locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters]; } NSLog(@"that's here"); [self.locationManager startUpdatingLocation]; } } - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { switch (status) { case kCLAuthorizationStatusNotDetermined: if ([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { [locationManager requestWhenInUseAuthorization]; } break; default: break; } } //定位代理經緯度回調 -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ [locationManager stopUpdatingLocation]; NSLog(@"location ok"); CLLocation *currentLocation = [locations firstObject]; NSLog(@"%@",[NSString stringWithFormat:@"經度:%3.5f\n緯度:%3.5f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude]); CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { for (CLPlacemark * placemark in placemarks) { NSDictionary *test = [placemark addressDictionary]; // Country(國家) State(城市) SubLocality(區) NSLog(@"%@", [test objectForKey:@"State"]); _locationCity.text = [test objectForKey:@"SubLocality"]; } }]; } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { if (error.code == kCLErrorDenied) { NSLog(@"location%ld",(long)error.code); } }
(5)設置開始定位結束定位
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self startLocation]; // 開始定位 } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [locationManager stopUpdatingLocation]; // 中止定位 }
若是還不能定位的歡迎留言交流!