这是我的代码,显示了 map 上当前位置的警告和蓝点:
MapName.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface MapName : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
@property (strong, nonatomic) IBOutlet MKMapView *MapName;
@property (strong, nonatomic) CLLocationManager *locationManager;
@end
MapName.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];
//Center the map
[self gotoLocation];
//Show current position
_MapName.showsUserLocation = YES;
}
我已经将
NSLocationWhenIsUseUsageDescription
键作为字符串添加到Info.plist中。我仍然在Xcode上遇到相同的错误。
最佳答案
这是由于两个原因:
[self.locationManager startUpdatingLocation];
和
_MapName.showsUserLocation = YES;
在调用这些权限之前,需要检查用户是否已授予权限。还要确保您关闭 Storyboard 上MKMapKit中的“用户位置”(这一步花了我几天时间进行跟踪)。
做类似的事情:
CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];
if (authorizationStatus == kCLAuthorizationStatusAuthorized ||
authorizationStatus == kCLAuthorizationStatusAuthorizedAlways ||
authorizationStatus == kCLAuthorizationStatusAuthorizedWhenInUse) {
[self.locationManager startUpdatingLocation];
_MapName.showsUserLocation = YES;
}
根据您的应用程序,您可能不希望在启动时要求用户的许可,因为不建议这样做。