didUpdateLocations方法没有被调用

时间:2019-01-28 15:12:29

标签: ios swift cllocationmanager

我的方法didUpdateLocations似乎从未被调用过?为什么是这样?我已将密钥添加到info.plist

这是我的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var locationManager = CLLocationManager()

    locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
    }



}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let locValue:CLLocationCoordinate2D = manager.location!.coordinate

    lat = locValue.latitude
    long = locValue.longitude

}

1 个答案:

答案 0 :(得分:3)

使locationManager为类变量。您在viewDidLoad中将其声明为局部变量,这意味着它将被立即释放,因为此函数之外没有强引用。

class YourViewController : UIViewController, CLLocationManagerDelegate 
{
    var locationManager : CLLocationManager?

    override func viewDidLoad() 
    {
        super.viewDidLoad()

        locationManager? = CLLocationManager()

        locationManager?.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled()
        {
            locationManager?.delegate = self
            locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager?.startUpdatingLocation()
        }
    }
}