【问题标题】:CLLocation Prompt shows and disappears in one momentCLLocation Prompt 在一瞬间显示和消失
【发布时间】:2016-07-19 18:01:08
【问题描述】:

在我的应用程序中,我尝试从 GPS 获取经度和纬度。为此,我必须询问用户是否有权访问他的位置。在我这样做之前,我添加到 Info.plist 这两个规则:Privacy - Location When In Use Usage DescriptionPrivacy - Location Always Usage Description,然后在 AppDelegate 我询问是否允许这样做(SWIFT 3.0):

if CLLocationManager.locationServicesEnabled() == true {
        let localisationManager = CLLocationManager()
        localisationManager.requestWhenInUseAuthorization()
        localisationManager.startUpdatingLocation()
    }

在运行应用程序时我可以看到UIAlertController 一会儿,但几乎在同一时间它消失了,我没有时间点击Allow 并且我无法使用 GPS。如何解决?

我的问题的有效解决方案:

我在class LocationManager and then I used it in function. 中创建了单独的变量var locationManager = CLLocationManager()

【问题讨论】:

    标签: ios swift core-location uialertcontroller ios10


    【解决方案1】:

    问题是在授权提示出现之前 localisationManager 对象正在被释放...requestWhenInUseAuthorization 以延迟方式运行,因此CLLocationManager 的这个实例从你下面被拉出。

    因此,将 localisationManager 的范围更改为您的 View Controller 类而不是本地变量。

    class ViewController: UIViewController {
     let localisationManager = CLLocationManager()    // <-- scope to class
    
     //...
     function requestAuthorization() {
       localisationManager.requestWhenInUseAuthorization() 
     }
    
    }
    

    您也可以将 CLLocationManager 限定为您的应用委托。

    WWDC 2016 视频 Core Location Best Practices 在会议第 21 分钟附近很好地解释了这一点。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 2022-10-26
    • 2019-02-20
    • 2015-08-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多