我试图在我的控制台中仅使用 NSLog
坐标,但它不起作用。
我在标题中链接了核心位置
@implementation ViewController {
CLLocationManager *locationManager;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (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) {
NSLog(@"%f", currentLocation.coordinate.longitude);
NSLog(@"%f", currentLocation.coordinate.latitude);
}
}
但我在控制台中没有得到任何信息,有人知道可能出了什么问题吗?
最佳答案
从 iOS 8 开始,您必须在开始更新位置之前请求用户的许可。
在此之前,您必须添加用户将收到的消息以及权限请求。在你的 .plist 文件中添加这两个键(如果你想使用两种类型的位置获取)并用你自己的消息填充它们:NSLocationWhenInUseUsageDescription
,NSLocationAlwaysUsageDescription
然后在启动 CLLocationManager 之前请求许可:
[self.locationManager requestWhenInUseAuthorization];
或/和
[self.locationManager requestAlwaysAuthorization];
为避免在 iOS 7 及以下版本上崩溃,您可以定义一个宏来检查操作系统版本:
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
然后你可以做:
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
现在它应该可以工作了。
关于iOS 8 CLLocationManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452785/