MapKit дает неправильный лат и язык - iOS 8

Когда я пытаюсь использовать карту в iOS 8, я становлюсь ниже ошибки.

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

Для этого я попробовал решение здесь, но все равно не повезло.

Ниже я это сделал.

Шаг 1. Войдите в Info.plist

NSLocationWhenInUseUsageDescription - This is test text

Шаг 2. Обновлено - (CLLocationCoordinate2D) getLocation

-(CLLocationCoordinate2D) getLocation{
    CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    // this is change
    if(IS_OS_8_OR_LATER) {
        [locationManager requestWhenInUseAuthorization];
    }
    [locationManager startUpdatingLocation];


    CLLocation *location = [locationManager location];
    CLLocationCoordinate2D coordinate = [location coordinate];

    return coordinate;
}

Шаг 3. Префикс .pch

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

Шаг 4. Удалите приложение снова с помощью ниже в viewDidLoad.

CLLocationCoordinate2D theCoordinate;
theCoordinate = [self getLocation];

NSLog(@"ffffff===%f===%f", theCoordinate.latitude, theCoordinate.longitude);

Тем не менее я получаю вывод как

ffffff===0.000===0.000

Примечание:

Я получаю предупреждение, но это всего лишь половина секунд и исчезает, а затем я получаю сообщение как

CLLocationCoordinate2D theCoordinate;
theCoordinate = [self getLocation];

NSLog(@"ffffff===%f===%f", theCoordinate.latitude, theCoordinate.longitude);

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

enter image description here

Любая идея, почему это происходит?

Я тестирую iPad 2 iOS 8.0 и симулятор iOS 8.0

Ответ 1

Не уверен, что было реальной проблемой, но поставил ниже код в viewDidLoad решить проблему.

mapView.delegate = self;
locationManager.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
#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];
}
#endif
[self.locationManager startUpdatingLocation];

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

Ссылка

Ответ 2

Вам нужно реализовать диспетчер делегатов CLLocationManager Delegate (- (void) locationManager: (CLLocationManager *), который сделалUpdateLocations: (NSArray *)), чтобы получить обновления местоположения.

Вот фрагмент кода для вашей справки:

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
     CLLocation *currentLocation = [locations lastObject];

     NSLog(@"ffffff===%f===%f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}

В качестве альтернативы вы можете реализовать метод Mapkit после делегата:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKUserLocation *myLocation = userLocation;
    NSLog(@"ffffff===%f===%f", myLocation.coordinate.latitude, myLocation.coordinate.longitude);
}

Ответ 3

requestWhenInUseAuthorization выполняется асинхронно, поэтому вы не должны вызывать startUpdatingLocation, пока не получите изменение статуса авторизации в своем делетете.

Ответ 4

Да! Получил решение. Вот мой весь код и добавленные вещи, чтобы заставить его работать. Особая благодарность @MBarton за его большую помощь. Также благодаря @Vinh Nguyen за то, что он инвестировал свое драгоценное время в решение моей проблемы.

Добавлена ​​ Структура размещения ядра в Целевая → Общие → Связанные структуры и библиотеки

Добавлен в файл .plist

NSLocationAlwaysUsageDescription

Смотрите скриншот:

plist screenshot

В моем ViewController.h

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

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

@interface ViewController : UIViewController  <MKMapViewDelegate,  CLLocationManagerDelegate>
{
    __weak IBOutlet UINavigationItem *navigationItem;
}

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

@end

Тогда в ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize mapView;

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

    [self setUpMap];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUpMap
{
    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 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];
}

Ufff...! Получил решение после борьбы со многими кодами за последние 5 дней...

Отсылается здесь