调用[locationManager requestWhenInUseAuthorization]时,警报视图会自动消失;

Fra*_*gle 33 core-location mapkit ios

我在打电话

[locationManager requestWhenInUseAuthorization];
Run Code Online (Sandbox Code Playgroud)

在显示MKMapView(showsUserLocation = YES)的屏幕上.这首先看起来很奇怪(Apple应该MKMapView自动处理这个问题,但是当我没有这样做时,XCode就会抱怨).

因此,我获得了警报视图,表明应用程序想要使用您的位置,但警报视图会自动消失.

为什么警报视图会自行消失?

我唯一能想到的事情是,我打电话requestWhenInUseAuthorizationinitWithCoder方法.我只是这样做,因为我认为从viewDidLoad调用它时我看到了Xcode的抱怨.

Pau*_*nne 95

你可能是ARC'd.确保您仍然具有对CLLocationManager的引用.您可以通过将其作为财产来轻松完成此操作.

ARC代表自动参考计数.在启用ARC的项目中(除非您正在处理一些非常旧的项目,或者您故意将其关闭,您的项目是一个启用ARC的项目),您需要保留对稍后将使用的对象的引用.CLLocationManager不返回单例,因此您需要在关注的类中保留对它的引用.像这样的东西:

@property (strong, nonatomic) CLLocationManager *locationManager
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Apple的ARC文档.(并且感谢Falko寻找与之相关的深层链接.)

我将Gobe的评论内联,以防您没有滚动阅读它.

对于Swift:不要创建一个本地范围的locationManager对象,而是将它作为关注类的属性,比如private let locationManager = CLLocationManager(),然后将它正常用作self.locationManager.requestWhenInUseAuthorization()

  • 对于Swift:不是创建一个本地作用域`locationManager`对象,而是将它作为你关心的类的属性,比如`private let locationManager = CLLocationManager()`,然后将它正常用作`self.locationManager.requestWhenInUseAuthorization()` (9认同)
  • 谢谢!我转移到Swift并认为CLLocationManager()返回了一个单例. (3认同)