【问题标题】:Getting the user's current location in iOS (no solution I've found is working)获取用户在 iOS 中的当前位置(我发现没有解决方案有效)
【发布时间】:2015-11-24 00:30:23
【问题描述】:

我正在尝试获取用户的当前位置并相应地设置地图视图,我觉得我已经尝试了所有方法但它不起作用。这是我得到的:

ViewController.h

@interface ViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (retain, nonatomic) CLLocationManager *locationManager;

ViewController.m

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

float latitude = self.locationManager.location.coordinate.latitude;
float longitude = self.locationManager.location.coordinate.longitude;
MKCoordinateRegion region;
region.center.latitude = latitude;
region.center.longitude = longitude;
region.span.latitudeDelta = SPAN_VALUE;
region.span.longitudeDelta = SPAN_VALUE;
[self.mapView setRegion:region animated:NO];



-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *currentLocation = [locations lastObject];
    NSLog(@"updated to location %f, %f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude);
}

Info.plist

我为 NSLocationAlwaysUsageDescription、NSLocationWhenInUseUsageDescription 和 Privacy - Location Usage Description 设置了字符串值。

模拟器

在“调试”下,我有一个自定义位置集的坐标,这是位置管理器应该检索的,对吧?我还检查了模拟器中的设置,并且我的应用程序在使用该应用程序时具有位置权限。但是,当我的地图加载视图时,它位于海洋中间的某个地方,甚至不靠近自定义位置。

我认为 updateLocations 方法甚至都没有运行,运行应用程序时没有 NSLog 输出。知道发生了什么吗?

**编辑:目标版本适用于 8.4,因为这是一个我无法更改的项目

【问题讨论】:

  • 你的代码没有意义。你做的一切都乱七八糟。你能解释一下为什么要在viewDidLoad 中设置地图视图的区域吗?这太快了,因为获取位置需要时间。另外,如果这是iOS 9,如果你只想一次性声明用户的位置,为什么不打电话给requestLocation
  • 它适用于 iOS 8 并且必须如此,我将添加它。而对于我刚刚脱离老师的代码的地区,那是他设置的地方。
  • 当你复制别人的代码时,其中的所有错误都是你的责任。
  • 哇,好吧,对不起,我的代码结构基于我的教授的结构。感谢您的帮助,而不是戏剧性的贡献。
  • 但是感谢 Matt 指出代码出错的地方,我将更改结构以便有时间更新。

标签: ios objective-c iphone xcode


【解决方案1】:

几乎在那里。正如一些 cmets 中提到的,您需要将区域更新代码移动到 -locationManager:didUpdateLocations:

除此之外,请确保您的所有 info.plist 键都拼写正确。如果不是,则该位置将永远不会更新,您也不会收到任何错误消息。此外,请检查以确保您的 mapView 插座实际连接到您的 XIB 或 Storyboard 文件中的 MKMapView。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2018-05-24
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多