无法在 iOS 8 中获取用户位置

Can't get user location in iOS 8

我正在尝试获取 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

有什么问题吗?

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

NSLocationWhenInUseUsageDescription = "your text"(可能是“”)

NSLocationAlwaysUsageDescription = "your text"(可能是“”)

将此添加到您的 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];
        }

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