2013-10-20 22 views
0

请问我该怎么做? 我在我的iPhone应用程序中有一个按钮,用户点击开始GPS导航。我点击按钮时所做的所有操作都是获取它们的位置,然后将其传递给Google地图来完成剩下的工作。Xcode GPS位置管理器访问消息

但是,只要我登陆屏幕上的按钮,应用程序问我标准的“这个应用程序想使用您的当前位置”。但我不想在我登陆屏幕时立即询问这个问题。相反,应该询问按钮何时被点击。

这里是我如何处理我的观点.m文件的场景:

- (void)viewDidLoad 
{ 
self.locationManager = [[CLLocationManager alloc] init]; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
locationManager.delegate = self; 
[locationManager startUpdatingLocation]; 

[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 
} 

,然后单击按钮时。也试图从viewDidLoad中放置代码,如从注释部分可以看到的那样。这工作,我不会问视图加载时的问题,但一旦点击按钮,GPS不起作用。我在应用程序屏幕上收到一条错误消息,提示“该应用程序无法建立到最近公路的路线”。 “这个应用程序想访问你当前的位置”只是简单地在屏幕上闪烁。

- (IBAction)gpsNavigation:(id)sender 
{ 
/* 
self.locationManager = [[CLLocationManager alloc] init]; 
locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
locationManager.delegate = self; 
[locationManager startUpdatingLocation]; 
*/ 

NSString *destAddress = @"52.269444, -9.708674"; 
NSString *url = [NSString stringWithFormat: @"http://maps.apple.com/maps?saddr=%f%f&daddr=%@", 
       locationManager.location.coordinate.latitude, 
       locationManager.location.coordinate.longitude, 
       [destAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]]; 
} 

回答

2

请使用gpsNavigation:method中的注释代码。 你的问题是,只要你调用[locationManager startUpdatingLocation],你就会得到locationManager.location。 所以你的代码可以如下。

- (IBAction)gpsNavigation:(id)sender 
{ 
    self.locationManager = [[CLLocationManager alloc] init]; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.delegate = self; 
    [locationManager startUpdatingLocation]; 
} 

- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    NSString *destAddress = @"52.269444, -9.708674"; 
    NSString *url = [NSString stringWithFormat: @"http://maps.apple.com/maps?saddr=%f%f&daddr=%@", 
        locationManager.location.coordinate.latitude, 
        locationManager.location.coordinate.longitude, 
        [destAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]]; 
    [locationManager stopUpdatingLocation]; 
} 
1

只要您致电[locationManager startUpdatingLocation]您的应用程序请求的位置,并会要求用户许可。所以延迟这个电话,直到你需要它(按下按钮)