Alert view disappears on its own when calling [locationManager requestWhenInUseAuthorization];

让人想犯罪 __ 提交于 2021-02-06 14:22:02

问题


I'm calling

[locationManager requestWhenInUseAuthorization];

on a screen that shows an MKMapView (showsUserLocation = YES). Which seems weird in the first place (Apple should handle this for MKMapView automatically, but XCode was complaining when I didn't do it).

So I get the alert view that says the application wants to use your location, but then the alert view disappears on its own.

Why does the alert view disappear on its own?

Only thing I can think of is that I am calling requestWhenInUseAuthorization in the initWithCoder method. I'm only doing that because I think I saw the Xcode complaint when calling it from viewDidLoad.


回答1:


You're probably being ARC'd. Make sure that you still have a reference to your CLLocationManager. You can easily do this by making it a property.

ARC stands for Automatic Reference Counting. In an ARC-enabled project (and unless you are working on something really old or you turned it off on purpose, your project is an ARC-enabled project) you need to keep references to objects that you'll use later on. CLLocationManager doesn't return a singleton so you need to keep a reference to it in your classes that care. Something like this:

@property (strong, nonatomic) CLLocationManager *locationManager

See Apple's ARC documentation for details. (And thanks Falko for hunting down the deep link to that.)

I'm putting Gobe's comment inline in case you didn't scroll to read it.

For Swift: instead of creating a local scope locationManager object, let it as a property of your classes that care, like private let locationManager = CLLocationManager() and then use it normally as self.locationManager.requestWhenInUseAuthorization()



来源:https://stackoverflow.com/questions/27048995/alert-view-disappears-on-its-own-when-calling-locationmanager-requestwheninusea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!