When trying to display of current location on the map after adding the requestWhenInUseAuthorization into the plist file, still I'm getting error:
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
I tried to solve several ways. But still failed. I am confused which part I am missing. My full code is:
I added a mapView on the top of view controller and then mapped it with .h file.
#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
Can any body please tell me which thing I am missing here. I'm new in iOS and I tried to solve couple of hours.
You need to call requestWhenInUseAuthorization or requestAlwaysAuthorization to prompt the user if he will allow location tracking. Then you need to handle the response and use location only if the user allows it.
It should look like this:
Try this,
Create an object for CLLocationManager.
Add the following code inside of your viewDidLoad.
locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [locationManager requestWhenInUseAuthorization]; }
Don't forgot to add
CLLocationManagerDelegate
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.