我正在尝试使用 Xcode 6.3.1 中的核心位置框架获取用户的当前位置,我做了以下事情:
- 在Target -> General -> Linked Frameworks & Libraries下添加了核心位置框架
我的ViewController.h文件如下图所示,
#import <UIKit/UIKit.h> #import <CoreLocation/CoreLocation.h> @interface ViewController : UIViewController<CLLocationManagerDelegate> @property (weak, nonatomic) IBOutlet UILabel *lblLatitude; @property (weak, nonatomic) IBOutlet UILabel *lblLongitude; @property (weak, nonatomic) IBOutlet UILabel *lblAddress; @property (strong, nonatomic) CLLocationManager *locationManager; @end
我的 ViewController.m 文件如下图所示,
- (void)viewDidLoad { [super viewDidLoad]; self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; if(IS_OS_8_OR_LATER){ NSUInteger code = [CLLocationManager authorizationStatus]; if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) { if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){ [self.locationManager requestAlwaysAuthorization]; } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) { [self.locationManager requestWhenInUseAuthorization]; } else { NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription"); } } } [self.locationManager startUpdatingLocation]; } #pragma mark - CLLocationManagerDelegate - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"didFailWithError: %@", error); UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [errorAlert show]; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"didUpdateToLocation: %@", newLocation); CLLocation *currentLocation = newLocation; if (currentLocation != nil) { lblLatitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; lblLongitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]; } } @end
我还在 info.plist 文件中添加了以下键
- NSLocationWhenInUseUsageDescription
- NSLocationAlwaysUsageDescription
所以,有没有人有解决这个问题的方法,请帮忙。一整天都在寻找这个而失去理智。