Swift没有达到LocationManager功能

时间:2016-02-10 10:16:25

标签: ios swift

我正在尝试获取我的位置,以便检查我距离某个经度和纬度有多远。

由于某种原因,程序永远不会到达我想要抓住坐标的LocationManager功能。

我已在info.plist中设置了正确的属性,该应用确实要求获得许可。

我添加了一个检查错误的函数并得到了:

  

didFailWithError错误Domain = kCLErrorDomain Code = 0"(null)"

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {


    var locationManager:CLLocationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.delegate = self

            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
            print("location on")

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        print("REACHED FUNCTION")

    }


}

1 个答案:

答案 0 :(得分:0)

如果您使用的是iOS 8.0及更高版本,则需要在开始更新位置之前申请许可。您可以使用以下代码

if #available(iOS 8.0, *) {
    locationManager.requestWhenInUseAuthorization()
}

以上代码将进入viewDidLoad。并实现以下委托方法

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status {
    case .AuthorizedWhenInUse:
        locationManager.startUpdatingLocation()
        break  
    case .AuthorizedAlways:
        locationManager.startUpdatingLocation()
        break
    default:
        break
    }
}