如何在iOS上获取当前位置?

我无法获得当前位置。 当我在不同的地方启动我的应用程序时,App可以获得最后的位置。 但我不想最后的位置。 如果您关闭应用并重新启动它,现在应用可以获取当前位置。 即使首次启动应用程序,我怎样才能获得当前位置?

- (void)viewDidLoad { [super viewDidLoad]; [locationManager startUpdatingLocation]; self.mapView.delegate = self; [self.mapView setShowsUserLocation:YES]; locationManager.delegate=self; locationManager = [[CLLocationManager alloc] init]; locationManager.delegate=self; locationManager.desiredAccuracy=kCLLocationAccuracyBest; locationManager.distanceFilter=kCLDistanceFilterNone; location = [locationManager location]; CLLocationCoordinate2D coord; coord.longitude = location.coordinate.longitude; coord.latitude = location.coordinate.latitude; lat = coord.latitude; longt = coord.longitude; } 

你正在做[locationManager startUpdatingLocation]; 在设置其委托之前

 locationManager = [[CLLocationManager alloc] init]; locationManager.delegate=self; locationManager.desiredAccuracy=kCLLocationAccuracyBest; locationManager.distanceFilter=kCLDistanceFilterNone; [locationManager startUpdatingLocation]; 

并实现其委托方法

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { } 

要获取当前位置及其坐标,您只需在viewDidLoad方法中执行此操作:

 - (void)viewDidLoad { [super viewDidLoad]; locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m [locationManager startUpdatingLocation]; } 

关于更新位置,请使用此方法:

  - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ // your code here... } 

您应该阅读位置感知编程指南中提供的文档。

具体来说,当您询问当前位置时,系统会立即返回最后一个已知位置,以便您可以使用它执行一些有用的操作。 如果您不关心过去的位置,则可以通过查看返回的CLLocationtimestamp属性来丢弃它并仅使用更新的位置信息来确定它的最近位置。

您应该真正阅读CLLocationManager文档。

您正在做的Wat将无法工作,因为需要一些时间来确定设备位置。 因此,您需要等到CLLocationManager通知您某个位置已被阻止。

您需要实现CLLocationManagerDelegate ,它将告诉您某个位置是否阻止或位置确定是否失败。

此外,您还应该检查位置是否可以阻止:

 if ([CCLocationManager locationServicesEnabled]) { // The location services are available. } 

您还应该检查是否授权您使用[CCLocationManager authorizationStatus]的位置服务。