2011-10-24 65 views
1

我想从我的代码连接到GPS。根据to this tutorial我这样做。获取经度和纬度值

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    CLController = [[CoreLocationController alloc] init]; 
    CLController.delegate = self; 
    [CLController.locMgr startUpdatingLocation]; 
} 

- (void)locationUpdate:(CLLocation *)location { 
    locLabel.text = [location description]; 
    } 

- (void)locationError:(NSError *)error { 
    locLabel.text = [error description]; 
    } 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    } 

上面的代码被放置在称为GetMyLocationViewController视图控制器,我有另一个视图控制器称为MainScreenViewController

当屏幕加载时,MainScreenViewController被加载,我将需要GPS位置继续操作该屏幕。

ViewDidLoad方法MainScreenViewController我写了以下;

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    GetMyLocationViewController *getMyLocationViewController = [[GetMyLocationViewController alloc]initwithXib:nil bundle:nil]; 

    [self.navigationController pushViewController:getMyLocationViewController Animation:YES]; 
    // AND THEN I NEED TO ACCESS THE LONGITUDE AND LATITUDE VALUES 

} 

当上述代码被执行,的MainScreenViewControllerviewDidLoad方法被执行,而不是locationUpdate方法。我能得到longitudelatitude的值的唯一方法是通过执行locationUpdate方法。那么我怎样才能得到这些价值呢?

回答

0

你在设备上测试过吗?版本4.2之前的xcode没有GPS模拟器,因为locationUpdate方法永远不会调用。

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 
    if([self.delegate conformsToProtocol:@protocol(CoreLocationControllerDelegate)]) { // Check if the class assigning itself as the delegate conforms to our protocol. If not, the message will go nowhere. Not good. 
     [self.delegate locationUpdate:newLocation]; 
    } 
} 
+0

那么你说'ViewDidLoad'后,'locationUpdate'被调用?并在调用ViewDidLoad后不退出? – sharon

+0

您需要实现在应答中复制的协议,此方法仅在GPS获取新坐标时才会更新。 – gfdgfd

+0

你是什么意思?我是新手:S请你详细说明 – sharon

0

您确定您正在加载您的GetMyLocationViewController?您的代码只显示加载MainScreenViewController,它在其-viewDidLoad方法中再次加载自身,这会导致无限循环加载并推送MainScreenViewControllers

更新:本教程中的CoreLocationController类似乎不必要。而是使用它,使CLLocationManager成为GetMyLocationViewController的一个属性。让GetMyLocationViewController的-viewDidLoad方法是这样的:

-(void)viewDidLoad { 
    [super viewDidLoad]; 

    self.locationManager = [[CLLocationManager alloc] init]; 
    self.locationManager.delegate = self; 
    [self.locationManager startUpdatingLocation]; 
} 

不要忘记导入CoreLocation库和实现委托方法。

+0

哦,对不起,我编辑了代码。我输入了错误的代码位(查找修改后的代码)。你有什么线索,我应该怎么做? – sharon