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

时间:2015-01-07 11:17:14

标签: ios objective-c mapkit

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

可能出现什么问题?

2 个答案:

答案 0 :(得分:2)

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

NSLocationWhenInUseUsageDescription =“您的文字”(可能是“”)

NSLocationAlwaysUsageDescription =“您的文字”(可能是“”)

答案 1 :(得分:2)

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

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