2013-12-21 2 views
0

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

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

Почему NSSC не печатает на консоль?

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

-(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 

ответ

3

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

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

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

+0

Благодарим вас за ответ, но если это так, то когда я иду на кнопку, не будет ли ярлык отображаться не на месте? Наверное, я смущен, почему кнопка и ярлык работают нормально, но NSLog не будет. – user3117509

+1

@ user3117509: В действии кнопки * вы * выбираете последнее местоположение, вызывая 'self.gpsLM.location'. Метод делегата вызывается из диспетчера местоположений (если задан делегат). –

+0

@ user3117509: Ответит ли это на ваш вопрос? Пожалуйста, дайте мне знать, если вам нужна дополнительная информация. –

Смежные вопросы