繁体   English   中英

将requestWhenInUseAuthorization添加到plist文件后,iOS地图视图给出错误

[英]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文件映射。

.h文件代码:

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

@interface ViewController : UIViewController <MKMapViewDelegate>

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

@end

.m文件代码:

#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来提示用户是否允许位置跟踪。 然后,只有在用户允许的情况下,您才需要处理响应并使用位置。

它看起来应该像这样:

  1. 查找授权状态
  2. 如果状态为CLAuthorizationStatus.NotDetermined,则调用requestWhenInUseAuthorization或requestAlwaysAuthorization并处理结果
  3. 如果授权状态为kCLAuthorizationStatusRestricted或kCLAuthorizationStatusDenied,则不允许您的应用使用位置服务,因此您应中止使用它们的尝试

https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/index.html#//apple_ref/occ/instm/CLLocationManager/requestWhenInUseAuthorization

尝试这个,

为CLLocationManager创建一个对象。

在viewDidLoad中添加以下代码。

locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [locationManager requestWhenInUseAuthorization]; }

不要忘记添加

CLLocationManagerDelegate

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM