簡體   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