【问题标题】:Why latitude and longitude is showing zero in ios 9?为什么纬度和经度在 ios 9 中显示为零?
【发布时间】:2021-05-15 14:27:08
【问题描述】:

我必须找到当前位置,我正在使用此代码

 -(CLLocationCoordinate2D) getLocation{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;

}

- (void)getCurrentLocation{
    CLLocationCoordinate2D coordinate = [self getLocation];
    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
    NSLog(@"Latitude  = %@", latitude);
    NSLog(@"Longitude = %@", longitude);
}

但是纬度和经度要归零了?我在viewDidLoad中调用了这些方法

[self getCurrentLocation];
[self getLocation];

为什么会这样,请帮助我。谢谢

【问题讨论】:

  • 如果你知道答案为什么要投反对票然后在这里发帖?
  • 你做错了。您需要使用CLLocationManagerDelegate 方法来获取坐标。你需要阅读Apple Doc
  • 我必须使用哪种方法?
  • @iphonic 我正在尝试但不工作告诉我该怎么做/
  • 怎么做:阅读文档。如果您需要有人告诉您,任何 Mac 也可以为您朗读文档。

标签: ios objective-c cllocationmanager


【解决方案1】:

希望以下信息对您有所帮助:

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

@interface yourController : UIViewController <CLLocationManagerDelegate> {
    CLLocationManager *locationManager;
}

@end

并添加:

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

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    [self.locationManager requestWhenInUseAuthorization];

[locationManager startUpdatingLocation];

回调函数

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude);
NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}

您还必须为

添加一个字符串
[`NSLocationAlwaysUsageDescription`]

【讨论】:

  • 没有错误来兄弟 didupdatelocations 没有执行
  • 谢谢@Suraj 但它一次又一次地更新如何停止它或如何设置计时器,以便在一段时间后它会更新
  • 这样设置--- locationManager.distanceFilter=20 (根据您的要求设置此值);它会过滤掉短距离移动。只有当用户移动超过 20 米时,您才会获得位置更新。
  • 我认为,locationManager.distanceFilter=(任何值);这解决了您的问题....但是如果您想了解有关计时器的更多信息,请使用此------- NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self 选择器:@selector(timerCalled) userInfo:nil 重复:不]; -(void)timerCalled { NSLog(@"Timer Called"); // 你的代码 }
【解决方案2】:

您需要使用“CLLocationManagerDelegate”。

只需阅读本教程。 How To Get the User Location in iPhone App

在这里您将了解CoreLocation Framework

这是返回当前纬度的委托方法。

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

还要确保您的应用授权使用位置服务。

并且还在设备上运行您的应用,或者如果您想在模拟器中查看结果,请按照教程中提到的步骤操作。

第 1 步#import &lt;CoreLocation/CoreLocation.h&gt; 导入框架。还要在您的项目中添加框架。

第 2 步:确保您的视图控制器实现 CLLocationManagerDelegate

@interface MyLocationViewController : UIViewController <CLLocationManagerDelegate>

第三步:定义CLLocationManager的类实例

@implementation MyLocationViewController {
    CLLocationManager *locationManager;
}

第 4 步

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    locationManager = [[CLLocationManager alloc] init];

    if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            //iOS 8.0 onwards
            [locationManager requestAlwaysAuthorization];
        }
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];
}

第 5 步:这是您的 CLLocationManagerDelegate 方法实现

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                                    initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {
       NSLog(@"Longitude %.8f",currentLocation.coordinate.longitude);
       NSLog(@"Latitude %.8f",currentLocation.coordinate.latitude);
    }
}

【讨论】:

  • 我正在使用你的方法,但仍然没有显示任何经纬度
  • 你是按照教程一步一步来的吗?
  • 我更新了我的答案。尝试这个。并在设备上运行您的应用程序。删除设备上以前存储的应用程序。检查设备中应用程序的权限。
  • 欢迎。如果我的回答有帮助,请将其标记为正确答案。
【解决方案3】:

首先转到您的 info.plist 并右键单击它并选择源代码选项。

然后在&lt;dict&gt;关键字后面加上以下几行

    <key>NSLocationAlwaysUsageDescription</key>
    <string>This App wants to Know your location</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>This App wants to Know your location</string>

没有这个,您将无法在 iOS 9.0 中使用 CLLocation。

现在按照说明进行操作。

导入

#import <CoreLocation/CoreLocation.h>

并列出类似的 CoreLocation 委托

@interface ViewController ()<CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *locationManager;

@end

然后在 viewDidLoad 方法中添加以下几行-

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

    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager startUpdatingLocation];

现在实现委托方法

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                               initWithTitle:@"Sorry" 
                               message:@"Failed to Get Your Location"      
                               delegate:nil 
                               cancelButtonTitle:@"OK"  
                               otherButtonTitles:nil];
    [errorAlert show];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {
        NSLog(@"%@", [NSString stringWithFormat:@"%.4f", currentLocation.coordinate.longitude]);
        NSLog(@"%@", [NSString stringWithFormat:@"%.4f", currentLocation.coordinate.latitude]);
    }
}

【讨论】:

    【解决方案4】:

    CLLocationManager 需要一些时间才能获得coordinates。因此,CLLocationManager 使用委托来通知它何时收到位置更新。因此,您无法立即获得结果。请查看this 的帖子,看看它是如何完成的。

    【讨论】:

      【解决方案5】:

      好吧,我希望您阅读doc,但我仍在发布解决方案。

      -(void)viewDidLoad{
           [self initLocationManager];
      }
      
      
      -(void)initLocationManager{
      
          self.locationManager=[[CLLocationManager alloc] init];
          self.locationManager.delegate=self;
          if (([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
              [_locationManager requestWhenInUseAuthorization];
          }
          self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
          self.locationManager.distanceFilter = kCLDistanceFilterNone;
          [self.locationManager startUpdatingLocation];
      
      }
      

      然后在CLLocationManager 委托方法中处理位置更新,如下所示

      -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
      
          // If it's a relatively recent event, turn off updates to save power.
          CLLocation* location = [locations lastObject];
          NSDate* eventDate = location.timestamp;
          NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
          if (abs(howRecent) < 15.0) {
      
      
              NSLog(@"%f,%f",location.coordinate.latitude,location.coordinate.longitude);
      
      
          }
      }
      

      更新

      要让它发挥作用,你需要做两件事

      1. Capabilities选项卡启用Background Modes,然后选择Location Updates,见下图

      2. 在信息选项卡中添加NSLocationWhenInUseUsageDescription,到plist中,见图

      它将开始工作。

      希望对您有所帮助。干杯。

      【讨论】:

      • 它不起作用兄弟没有显示任何东西,即使方法没有执行
      • -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ 这个方法没有执行
      • @aakash 查看我的更新。
      • 它现在正在工作非常感谢您的帮助,但是如何在 0.1 毫秒内一次又一次地停止更新纬度和经度
      • 只需调用 [self.locationManager stopUpdatingLocation];当你想停止它时。
      【解决方案6】:

      使用这个代码就可以了

      首先在info.plist中添加NSLocationAlwaysUsageDescription作为字符串

      在.h中

      #import <CoreLocation/CoreLocation.h>
      
      @interface ExamListVC : UIViewController<CLLocationManagerDelegate>
      {
          CLLocationManager * locationManager;
      }
      @end
      

      在 .m 中使用此代码

      - (void)viewDidLoad
      {
          [super viewDidLoad];
          // Do any additional setup after loading the view.
          locationManager . delegate = self;
      
          [self initLocationManager];
      }
      
          -(void)initLocationManager
          {
              locationManager=[[CLLocationManager alloc] init];
              locationManager.delegate=self;
              if (([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]))
              {
                  [locationManager requestWhenInUseAuthorization];
              }
              locationManager.desiredAccuracy = kCLLocationAccuracyBest;
              locationManager.distanceFilter = kCLDistanceFilterNone;
              [locationManager startUpdatingLocation];
      
          }
      
      
          -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
          {
              CLLocation* location = [locations lastObject];
              NSDate* eventDate = location.timestamp;
              NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
              if (abs(howRecent) < 15.0)
      
              {
                  NSLog(@"Current Coordinates are  %f,%f",location.coordinate.latitude,location.coordinate.longitude);
                  [locationManager stopUpdatingLocation];
                  }
              }
      

      它会给出类似的输出

      [2390:96060] 当前坐标为 37.332331,-122.031219

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多