2015-05-17 1 views
15

Я пытаюсь получить текущее местоположение пользователя с помощью Core Location Framework в Xcode 6.3.1, я следующие вещи:Основные методы Местоположение делегат не вызывался в прошивкой 8.3 Xcode 6.3.1

  1. Добавлено Core Location Framework под Target ->Общие ->Linked Каркасы & Библиотеки
  2. Мои ViewController.h файл, как показано ниже,

    #import <UIKit/UIKit.h> 
    #import <CoreLocation/CoreLocation.h> 
    
    @interface ViewController : UIViewController<CLLocationManagerDelegate> 
    @property (weak, nonatomic) IBOutlet UILabel *lblLatitude; 
    @property (weak, nonatomic) IBOutlet UILabel *lblLongitude; 
    @property (weak, nonatomic) IBOutlet UILabel *lblAddress; 
    @property (strong, nonatomic) CLLocationManager *locationManager; 
    
    @end 
    
  3. Мой файл ViewController.m как показано ниже,

    - (void)viewDidLoad 
    { 
    
    [super viewDidLoad]; 
    self.locationManager = [[CLLocationManager alloc] init]; 
    
    self.locationManager.delegate = self; 
    if(IS_OS_8_OR_LATER){ 
        NSUInteger code = [CLLocationManager authorizationStatus]; 
        if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) { 
        if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){ 
         [self.locationManager requestAlwaysAuthorization]; 
        } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) { 
         [self.locationManager requestWhenInUseAuthorization]; 
        } else { 
         NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription"); 
        } 
    } 
    } 
    [self.locationManager startUpdatingLocation]; 
    } 
    
    #pragma mark - CLLocationManagerDelegate 
    
    - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
    { 
        NSLog(@"didFailWithError: %@", error); 
        UIAlertView *errorAlert = [[UIAlertView alloc] 
             initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
        [errorAlert show]; 
    } 
    
    - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
    { 
        NSLog(@"didUpdateToLocation: %@", newLocation); 
        CLLocation *currentLocation = newLocation; 
    
        if (currentLocation != nil) { 
         lblLatitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]; 
         lblLongitude.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]; 
        } 
    } 
    @end 
    

Я также добавил следующие ключи в моем файле info.plist

  • NSLocationWhenInUseUsageDescription
  • NSLocationAlway sUsageDescription

plist image

Checked все дано here, here, here, here, и многое другое список

Итак, любое лицо, имеющее решение для этой проблемы, пожалуйста, помогите. Я потерял рассудок в поисках этого в течение всего дня.

+0

Значения для описания использования пустые. Вы уверены, что положили их? Также почему у вас есть два описания использования? –

+0

@VinhNguyen Я тоже пытался помещать значения в это, но это не влияет, и, сохраняя только NSLocationAlwaysUsageDescription, также и это не работает для меня. Пробовал это тоже ... – iYoung

+0

Попробуйте удалить if if if (code == kCLAuthorizationStatusNotDetermined && .... 'и просто вызвать либо' requestAlwaysAuthorization', либо 'requestWhenInUseAuthorization' на вашем экземпляре' locationManager' –

ответ

6

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

Добавлено Core Location Framework под мишенями> Общие-> Linked Frameworks & Библиотеки

Добавлено в .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) { 
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) { 
     // 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 дней ...

+0

Не используйте 'IS_OS_8_OR_LATER'. Есть правильные способы проверить, доступен ли API или нет. – rmaddy

+0

@rmaddy Обновил мой код, любезно просмотрел и предоставил ценные предложения. Спасибо, что сообщили мне об этом. – iYoung

+0

Это лучше. Я полностью удалю все ссылки на эти макросы из вашего ответа. – rmaddy