didUpdateLocations未调用

时间:2013-10-27 23:03:38

标签: ios objective-c xcode cllocationmanager cllocation

我试图获取当前位置,但是从未调用didUpdateLocations中的断点。

的LocationManager:

locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setDesiredAccuracy:kCLDistanceFilterNone];
[locationManager startUpdatingLocation];

委托方法:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

我确认了位置服务并启用并授权。

为什么没有按照它应该调用locationManager委托方法?

谢谢, 麦克

8 个答案:

答案 0 :(得分:68)

此外,在iOS8中,你必须有两件额外的东西:

  • Info.plist添加密钥,并请求位置管理员授权启动。

    • NSLocationWhenInUseUsageDescription

    • NSLocationAlwaysUsageDescription

  • 您需要请求相应位置方法的授权。

    • [self.locationManager requestWhenInUseAuthorization]

    • [self.locationManager requestAlwaysAuthorization]

代码示例:

self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
// Check for iOS 8. Without this guard the code will crash with "unknown selector" on iOS 7.
if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
    [self.locationManager requestWhenInUseAuthorization];
}
[self.locationManager startUpdatingLocation];

来源:http://nevan.net/2014/09/core-location-manager-changes-in-ios-8/

答案 1 :(得分:30)

当我遇到此问题时,这是由于线程问题造成的。

确保在主线程上调用所有这些方法。 非常重要的是,不仅要在主线程上调用startUpdatingLocation方法,还要调用其他方法。

您可以通过将代码包装在

中来强制代码在主线程上运行
dispatch_sync(dispatch_get_main_queue(), ^{

});

另请查看this answer

答案 2 :(得分:9)

确保将CLLocationManager添加为属性。

@property (nonatomic , strong) CLLocationManager *locationManager;

答案 3 :(得分:6)

是的,该属性是我的解决方案,并且最好检查位置服务是否已启用:

if ([CLLocationManager locationServicesEnabled]) {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [self.locationManager startUpdatingLocation];
}

答案 4 :(得分:2)

您必须告诉模拟器要模拟的位置。如果您没有指定位置,则CLLocationManager委托方法永远不会被调用。您可以使用模拟器菜单Debug - >地点。同样在调试区域的Xcode中,从Xcode运行应用程序时会出现一个小位置箭头。您可以使用它来指定GPX文件来模拟运动(尽管它仍然与真实设备不同)。

https://devforums.apple.com/message/1073267#1073267

答案 5 :(得分:2)

请注意,在iOS 11及更高版本中,必须向您的info.plist提供第三个密钥:NSLocationAlwaysAndWhenInUseUsageDescription

答案 6 :(得分:1)

如果设置了CLLocationManagerDelegate,则还设置了MapView Delegate

同时检查模拟器的位置,点击模拟器>调试>地点, 如果没有改变城市运行或高速公路驾驶。它对我有用。

答案 7 :(得分:0)

在我将didUpdateLocations的{​​{1}}属性更改为{{1}的属性后,我的应用程序有时在第一次拨打desiredAccuracy时经历了几分钟的延迟}:

CLLocationManager

将其更改回kCLLocationAccuracyKilometer之后,再次立即开始立即调用myLocationManager.desiredAccuracy = kCLLocationAccuracyKilometer; [myLocationManager startUpdatingLocation]; // Occasional long delay

kCLLocationAccuracyBest