【问题标题】:Can't get user location in iOS 8无法在 iOS 8 中获取用户位置
【发布时间】:2015-03-05 06:38:44
【问题描述】:

我正在尝试在 iOS 8 中获取用户位置,但我收到以下错误代码:尝试在不提示位置授权的情况下启动 MapKit 位置更新。必须先调用 -[CLLocationManager requestWhenInUseAuthorization] 或 -[CLLocationManager requestAlwaysAuthorization]。

我已经在我的代码中调用了这些方法,并且我还在我的 Info.plist 文件中创建了必要的条目。可能是什么问题?

这是我的代码:

ViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface ViewController : UIViewController <MKMapViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) IBOutlet MKMapView *mapView;
@property (nonatomic,strong) CLLocationManager *locationManager;

@end

还有我的 ViewController.m

#import "ViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>



@interface ViewController ()

@end

@implementation ViewController
@synthesize mapView;
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)


- (void)viewDidLoad {
    [super viewDidLoad];
    self.mapView.delegate = self;

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    if(IS_OS_8_OR_LATER) {
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager requestAlwaysAuthorization];
    }
    [self.locationManager startUpdatingLocation];

    self.mapView.showsUserLocation = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end

可能出了什么问题?

【问题讨论】:

  • 您是否已将 NSLocationAlwaysUsageDescription 键添加到您的属性列表中?
  • 您应该请求“使用时”或“始终”授权——不能同时请求两者。另外我建议您使用respondsToSelector 来确定授权方法是否可用,而不是检查iOS 版本。您是否设置了断点以确认正在调用授权请求方法?

标签: ios objective-c mapkit


【解决方案1】:

将此添加到您的 plist

<key>NSLocationAlwaysUsageDescription</key>
<string></string>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>

还有这行代码

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)


    if(IS_OS_8_OR_LATER) {
            [locationManager requestAlwaysAuthorization];
        }

这对我有用。希望对你也有用:)

【讨论】:

    【解决方案2】:

    现在您需要在 info.plist 文件中添加更多项目:

    NSLocationWhenInUseUsageDescription = "你的文字"(可能是" ")

    NSLocationAlwaysUsageDescription = "你的文字"(可能是" ")

    【讨论】:

      猜你喜欢
      • 2014-09-03
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多