CLAuthorizationStatus AuthorizedWhenInUse仅首次调用

时间:2015-05-16 00:13:48

标签: swift ios8 cllocationmanager

如果我没有请求" AuthorizedWhenInUse"这是一个问题。状态一旦我的应用程序第一个视图控制器被加载,我将永远不会得到更新。

我们说我有一个地图视图控制器。当我在viewDidLoad方法中询问状态时,它会更新我的位置,即调用func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)

现在我添加了一个介绍视图控制器,一旦用户完成介绍他/她将转到旧的地图控制器。但现在不再调用func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)了!

我注意到,如果我为我的应用程序手动设置和切换授权状态,然后返回我的应用程序,则会调用didUpdateLocations

class MapViewController: UIViewController, CLLocationManagerDelegate {

    private let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.distanceFilter = 100
        locationManager.delegate = self
        // >=iOS8
        if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
            locationManager.requestWhenInUseAuthorization()
        } else {
            locationManager.startUpdatingLocation()
        }
    }

    // MARK: - CLLocationManagerDelegate

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

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        if let location = locations.first as? CLLocation {
            println("User's location: \(location.description)")
        } else {
            println("User's location is unknown")
        }
    }

}

1 个答案:

答案 0 :(得分:1)

我发布了您发布的内容的几个问题,这里只有两个:

  1. 您正在从locationManager.startUpdatingLocation()调用viewDidLoad这只会在视图尚未加载到内存中时触发。建议将其移至viewWillAppear,以便每次都触发。
  2. 此代码应重写:

        if (locationManager.respondsToSelector(Selector("requestWhenInUseAuthorization"))) {
            locationManager.requestWhenInUseAuthorization()
        } else {
            locationManager.startUpdatingLocation()
        }
    
  3. 您需要检查authorizationStatus,如果是kCLAuthorizationStatusNotDetermined,则使用上面的if语句请求权限。如果您不是iOS 8,则用户将始终进入requestWhenInUseAuthorization部分。您不希望这样,因为操作系统只会请求一次许可。除非您在“设置”下停留手机位置隐私,否则不会再次询问。