NSLog CLLocation не печатается при запуске, только при нажатии кнопки

Мое приложение отображает последние известные/текущие координаты пользователя в текстовой метке при нажатии кнопки.

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

Почему NSLog не выводит на консоль?

Вот фрагмент кода, который должен печатать местоположение в журнале, когда приложение запускается и пользователь разрешает приложению доступ к своему местоположению:

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

CLLocation * currentLocation = [locations lastObject];

NSLog(@"%f", currentLocation.coordinate.latitude);

Ниже приведен мой полный код ViewController.h:

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


@interface ViewController : UIViewController <CLLocationManagerDelegate>

@property (nonatomic, strong) IBOutlet UILabel * gpsLabel;
@property (nonatomic, strong) CLLocationManager * gpsLM;

-(IBAction)gpsButton;

@end

А вот мой полный код ViewController.m:

#import "ViewController.h" //This imports the all of the code we have typed in the     ViewController.h file.
#import <CoreLocation/CoreLocation.h> //This imports the CoreLocation framework needed for    location apps.


//This assigns the Location Manager's delegate to this view controller

@interface ViewController () <CLLocationManagerDelegate>

//This tells the delegate that new location data is available. Manager is the object that updates the event, and the locations object is where the array of location data is stored.

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray    *)locations;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    //This allocates memory for and initializes the gpsLM object we setup in ViewController.h
    //This means that we can now use the object and do things with it.

    self.gpsLM = [[CLLocationManager alloc]init];

    //This calls a startUpdatingLocation method for our CLLocationManager object called gpsLM.
    //Because this is all in viewDidLoad, it all gets executed right away as soon as the app    is opened.

    [self.gpsLM startUpdatingLocation];

}

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


//This executes the instance method that we declared above in the header.
//Now we are actually implementing the method and can tell it what we want it to do.

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{

    //This creates an object called currentLocation and sets it's value to whatever the last  value is in the locations array.
    //Notice how it is also calling a method of lastObject for the object called locations.
    //So remember that you can set variables and objects equal to the result of a method call.

    CLLocation * currentLocation = [locations lastObject];

    //This prints out text to the debug console that states the latitude coordinate of the user's iPhone.

    NSLog(@"%f", currentLocation.coordinate.latitude);

}


-(IBAction)gpsButton{

    CLLocation * currentLocation = self.gpsLM.location;

    self.gpsLabel.text = [NSString stringWithFormat:@"Your Location is %@", currentLocation];

}

@end

person user3117509    schedule 21.12.2013    source источник


Ответы (1)


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

self.gpsLM = [[CLLocationManager alloc]init];
self.gpsLM.delegate = self; // <-- ADD THIS
[self.gpsLM startUpdatingLocation];

Без этого назначения диспетчер местоположения не знает, какому объекту передать обновление местоположения. Метод locationManager:didUpdateLocations: никогда не запускается.

person Martin R    schedule 21.12.2013
comment
Спасибо за ответ, но если это так, то когда я нажимаю кнопку, разве метка не отображает местоположение? Я думаю, я смущен, почему кнопка и метка работают нормально, а NSLog - нет. - person user3117509; 21.12.2013
comment
@ user3117509: В действии кнопки вы получаете самое последнее местоположение, вызывая self.gpsLM.location. Метод делегата вызывается из диспетчера местоположения (если был установлен делегат). - person Martin R; 22.12.2013
comment
@ user3117509: Это ответ на твой вопрос? Пожалуйста, дайте мне знать, если вам нужна дополнительная информация. - person Martin R; 23.12.2013
comment
Я все еще немного смущен, но я думаю, что действительно понимаю это. У меня сложилось впечатление, что все, что мне действительно нужно было сделать, это добавить ‹CLLocationManagerDelegate› в ViewController, и все. Вы хотите сказать, что каждый раз, когда я инициализирую новый объект класса CLLocationManager, если я хочу использовать данные обновления местоположения, мне нужно назначить делегата для их получения? - person user3117509; 23.12.2013
comment
@ user3117509: <CLLocationManagerDelegate> является лишь частью объявления и сообщает компилятору, что этот объект соответствует протоколу. Это ничего не делает во время выполнения. И да, вы должны назначить делегата объекту диспетчера местоположения. - person Martin R; 23.12.2013
comment
Извините за задержку ответа. Да, это сработало отлично, и я очень ценю вашу помощь, Мартин. Ваше здоровье. - person user3117509; 23.12.2013