【问题标题】:Prompt user to allow location services after being denied without crashing在被拒绝后提示用户允许定位服务而不崩溃
【发布时间】:2016-08-09 13:12:46
【问题描述】:

我面临的问题是,当我按下 UIButton 时 - 需要定位服务来启动操作。但是,如果用户在应用首次启动时拒绝定位服务 - 应用将会崩溃。

我已经尝试找到一种方法来实现 CLAuthorizationStatus .Denied 但我似乎找不到这样做的方法。我似乎可以实现的唯一代码是 didChangeAuthorizationStatus,它只在应用程序的首次启动时启动请求。

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
    if status == .AuthorizedAlways || status == .AuthorizedWhenInUse
    {
        manager.startUpdatingLocation()
    }
    else
    {
        manager.requestWhenInUseAuthorization()
    }
}

如果我按下 UIButton 发送 API 请求,如果位置服务被拒绝,应用程序将会崩溃。

我的问题是如何在按钮的 IBAction 中实现一种方法,该方法将引导用户转到他们的设置并启用位置服务。 :)

【问题讨论】:

  • 你到底想解决什么问题?
  • 如果使用位置服务的权限被拒绝并按下按钮 -> 显示警报以说明使用应用程序需要用户位置并将用户重定向到设置以进行更改。
  • 当你尝试else if status == .Denied时发生了什么?
  • 当我尝试 if status == .Denied 没有任何实际改变并且它从未呈现控制器时,我尝试将其放在括号中。此方法将在应用程序最初安装并自行运行时出现。我不确定如何甚至是否可以在按钮的 IBAction 方法中创建 CLAuthorizationStatus 的实例。
  • 我已经在 IBAction 中尝试过 - 让 status : CLAuthorization status 并实现一个 switch 语句来尝试 switch status { case .Denied ....etc... 但在这种方法中没有找到运气

标签: ios swift core-location cllocationmanager location-services


【解决方案1】:

CLLocationManager 有一个静态函数authorizationStatus(),您可以使用它来获取当前授权状态,甚至无需初始化CLLocationManager 对象。

因此,在用户按下按钮时调用的函数中,您可以检查授权状态并采取相应措施:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    lazy var locationManager = CLLocationManager()

    ...

    func didPressButton(sender: UIButton) {
        switch CLLocationManager.authorizationStatus() {
        case .AuthorizedAlways, .AuthorizedWhenInUse:
            locationManager.delegate = self
            locationManager.startUpdatingLocation()
        case .NotDetermined:
            locationManager.delegate = self
            locationManager.requestWhenInUseAuthorization()
        case .Denied:
            print("Show Alert with link to settings")
        case .Restricted:
            // Nothing you can do, app cannot use location services
            break
        }
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedWhenInUse {
            manager.startUpdatingLocation()
        }
    }
}

【讨论】:

  • 太棒了!非常感谢!! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 2017-07-01
  • 2013-05-10
  • 2022-01-15
  • 1970-01-01
  • 2013-04-09
相关资源
最近更新 更多