IOS 8 Map Kit Obj-C не может получить пользователей

Я работаю с Map Kit в iOS 8, используя Obj-C NOT SWIFT. Я не могу получить местоположение устройства, он установлен на 0.00, 0.00, и я получаю сообщение об ошибке:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

Я реализовал: (я пробовал только один за раз и не повезло)

if(IS_OS_8_OR_LATER) {
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation]; 

И в info.plist

NSLocationWhenInUseUsageDescription  :   App would like to use your location.
NSLocationAlwaysUsageDescription  :  App would like to use your location.

Мне будет предложено разрешить приложению использовать мое местоположение, но после того, как я соглашусь, ничего не изменится. Место указывается как 0,00, 0,00.

Код для отображения местоположения пользователей:

//Get Location
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager startUpdatingLocation];

MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = self.locationManager.location.coordinate.latitude;
region.center.longitude = self.locationManager.location.coordinate.longitude;
region.span.longitudeDelta = 0.005f;
region.span.longitudeDelta = 0.005f;
[mapView setRegion:region animated:YES];

Майк.

** РЕДАКТИРОВАТЬ: Просмотреть ответ ниже.

Ответ 1

Я заработал. Я разместил свой код ниже, чтобы помочь кому-либо еще иметь проблемы.

Вот мой полный код, чтобы получить представление MapKit Map View в iOS 8.

В вашем AppName-Info.plist Добавьте новую строку с именем ключа:

NSLocationWhenInUseUsageDescription

Или

NSLocationAlwaysUsageDescription

Со значением, являющимся строкой сообщения, которое вы хотите отобразить:

YourAppName would like to use your location.

В файле заголовка. (Я использую App Name-Prefix.pch, но YourViewController.h тоже будет работать)

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

YourViewController.h

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

@interface YourViewController : UIViewController <MKMapViewDelegate,  CLLocationManagerDelegate> {

}


@property(nonatomic, retain) IBOutlet MKMapView *mapView;
@property(nonatomic, retain) CLLocationManager *locationManager;

YourViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.


    mapView.delegate = self;
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    #ifdef __IPHONE_8_0
    if(IS_OS_8_OR_LATER) {
         // Use one or the other, not both. Depending on what you put in info.plist
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager requestAlwaysAuthorization];
    }
    #endif
    [self.locationManager startUpdatingLocation];

    mapView.showsUserLocation = YES;
    [mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];

    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locationManager startUpdatingLocation];
    NSLog(@"%@", [self deviceLocation]);

    //View Area
    MKCoordinateRegion region = { { 0.0, 0.0 }, { 0.0, 0.0 } };
    region.center.latitude = self.locationManager.location.coordinate.latitude;
    region.center.longitude = self.locationManager.location.coordinate.longitude;
    region.span.longitudeDelta = 0.005f;
    region.span.longitudeDelta = 0.005f;
    [mapView setRegion:region animated:YES];

}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
}
- (NSString *)deviceLocation {
    return [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
}
- (NSString *)deviceLat {
    return [NSString stringWithFormat:@"%f", self.locationManager.location.coordinate.latitude];
}
- (NSString *)deviceLon {
    return [NSString stringWithFormat:@"%f", self.locationManager.location.coordinate.longitude];
}
- (NSString *)deviceAlt {
    return [NSString stringWithFormat:@"%f", self.locationManager.location.altitude];
}

Наслаждайтесь!

- Майк

Ответ 2

Он нигде не написан, но если ваше приложение начинается с MapKit, вы все равно получите сообщение об ошибке "Попытка запускать обновления местоположения MapKit без запроса авторизации местоположения" даже после выполнения ответа MBarton. Чтобы избежать этого, вам нужно создать новый контроллер представления перед MapKit и реализовать там делегатов менеджера местоположений. Я назвал его AuthorizationController.

Итак, в AuthorizationController.h:

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

@interface MCIAuthorizationController : UIViewController <CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *locationManager;

@end

И в AuthorizationController.m:

- (void)viewDidLoad {
    [super viewDidLoad];

    // Location manager
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;

    // Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
}

#pragma mark - Location Manager delegates

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    NSLog(@"didUpdateLocations: %@", [locations lastObject]);
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"Location manager error: %@", error.localizedDescription);
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self.locationManager startUpdatingLocation];
        [self performSegueWithIdentifier:@"startSegue" sender:self];
    } else if (status == kCLAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location services not authorized"
                                                        message:@"This app needs you to authorize locations services to work."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    } else
        NSLog(@"Wrong location status");
}

Ответ 3

Попробуйте следующее:

 (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {

    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        self.mapView.showsUserLocation = YES;
    }

Ответ 4

Ваш код выглядит отлично, хотя вам не нужно вызывать requestWhenInUseAuthorization и другую requestAlwaysAuthorization, выберите тот, который вам нужен.

Код для отображения местоположений еще только выделяет locationManager, не ожидайте мгновенного получения данных о местоположении.

вам нужно подождать до вызова метода делегата: -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
, то также будет установлено self.locationManager.location.

Ответ 5

В ответ Майксу я обнаружил, что использование как [self.locationManager requestWhenInUseAuthorization];, так и [self.locationManager requestAlwaysAuthorization];, как показано в его коде, не работает. Вы должны использовать только ОДИН.

Я предполагаю, что некоторые дальнейшие изменения были сделаны с более поздней/стабильной версией API.

Ответ 6

У меня была та же проблема, но добавление этих двух строк в файл plist решило мои проблемы

NSLocationWhenInUseUsageDescription

и

NSLocationAlwaysUsageDescription

ПРИМЕЧАНИЕ. Должно быть указано строковое описание обоих этих значений. Вы можете использовать любой из них в вашем файле контроллера, как показано ниже.

self.locationManager= [[CLLocationManager alloc] init];
self.locationManager.delegate=self;
[self.locationManager requestAlwaysAuthorization];

Вы должны реализовать CLLOcationManagerDelegate в своем контроллере для доступа к этой функции

Ответ 7

Чтобы расширить принятый ответ, и если вы создадите образец проекта только с приведенной выше функциональностью, то помимо структур CoreLocation и Mapkit вам может потребоваться добавить рамки UIKit, Foundation и CoreGraphics вручную, а также в Xcode 6.

Ответ 8

Собственно, я изучаю лекцию CS193P Lecture 16, которая касается местоположения и отображения карты, и я не мог заставить менеджера местоположений работать в iOS 8, применяя то, что было в видео. Глядя на ваш ответ, я мог бы заставить его работать.

Info.plist был изменен, как описано в ответах (я использую NSLocationWhenInUseUsageDescription).

В AddPhotoViewController.hn добавлен параметр:

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

В AddPhotoViewController.m следующий код был добавлен в ViewDidLoad (после self.image):

#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER)
{
    [self.locationManager requestWhenInUseAuthorization];
}
#endif

Авторизация будет запрашиваться только один раз, при первом запуске приложения.

В AddPhotoViewController.h также было добавлено следующее: в лекции 16 оно не было сказано:

@property (nonatomic) NSInteger locationErrorCode;

shouldPerformSegueWithIdentifier был изменен, чтобы включить else if (! self.location):

else if (![self.titleTextField.text length])
        {
            [self alert:@"Title required"];
            return NO;
        }
        else if (!self.location)
        {
            switch (self.locationErrorCode)
            {
                case kCLErrorLocationUnknown:
                    [self alert:@"Couldn't figure out where this photo was taken (yet)."]; break;
                case kCLErrorDenied:
                    [self alert:@"Location Services disabled under Privacy in Settings application."]; break;
                case kCLErrorNetwork:
                    [self alert:@"Can't figure out where this photo is being taken.  Verify your connection to the network."]; break;
                default:
                    [self alert:@"Cant figure out where this photo is being taken, sorry."]; break;
            }
            return NO;
        }
        else
        { // should check imageURL too to be sure we could write the file
            return YES;
        }
Добавлен

didFailWithError:

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    self.locationErrorCode = error.code;
}