[英]iOS map view is giving error after adding requestWhenInUseAuthorization into plist file
将requestWhenInUseAuthorization添加到plist文件后尝试在地图上显示当前位置时,仍然出现错误:
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
我试图解决几种方法。 但是还是失败了。 我很困惑我缺少哪一部分。 我的完整代码是:
我在视图控制器的顶部添加了mapView,然后将其与.h文件映射。
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface ViewController : UIViewController <MKMapViewDelegate>
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize mapView = _mapView;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.mapView.userLocation self];
[self.mapView setShowsUserLocation:YES];
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
CLLocationCoordinate2D loc = [userLocation coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 500, 500);
[self.mapView setRegion:region animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
任何人都可以告诉我我在这里想念的是什么。 我是iOS的新手,所以尝试解决了几个小时。
您需要调用requestWhenInUseAuthorization或requestAlwaysAuthorization来提示用户是否允许位置跟踪。 然后,只有在用户允许的情况下,您才需要处理响应并使用位置。
它看起来应该像这样:
尝试这个,
为CLLocationManager创建一个对象。
在viewDidLoad中添加以下代码。
locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [locationManager requestWhenInUseAuthorization]; }
不要忘记添加
CLLocationManagerDelegate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.