经常调用Swift CLLocationManager(didUpdateLocations)

时间:2016-02-17 22:16:37

标签: swift delegates mapkit core-location cllocationmanager

任何人都可以解释,为什么委托方法' CLLocationManager(didUpdateLocations)'被叫4次虽然我立即停止更新?我只需要当前位置一次:)

import UIKit
import MapKit

class ContactView: UIViewController, CLLocationManagerDelegate {

    let clLocationManager = CLLocationManager()

    var latitude: AnyObject = 0.000000
    var longitude: AnyObject = 0.000000

    override func viewDidLoad() {
        super.viewDidLoad()
        self.nameTextField.delegate = self
        clLocationManager.delegate = self
        clLocationManager.desiredAccuracy = kCLLocationAccuracyBest
        clLocationManager.requestWhenInUseAuthorization()
        clLocationManager.startUpdatingLocation()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
            (placemarks, error) -> Void in
            self.clLocationManager.stopUpdatingLocation()
            if placemarks!.count > 0 {
                self.latitude = (manager.location?.coordinate.latitude)!
                self.longitude = (manager.location?.coordinate.longitude)!
                print(self.latitude)
                print(self.longitude)
            } else {
                print("Error")
            }
        })
    }
}

谢谢!

2 个答案:

答案 0 :(得分:2)

尝试将stopUpdatingLocation从reverseGeocodeLocation

移到外面
 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    manager.stopUpdatingLocation()
    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
                (placemarks, error) -> Void in
                if placemarks!.count > 0 {
                    self.latitude = (manager.location?.coordinate.latitude)!
                    self.longitude = (manager.location?.coordinate.longitude)!
                    print(self.latitude)
                    print(self.longitude)
                } else {
                    print("Error")
                }
            })
        }
    }

答案 1 :(得分:1)

您需要更改以下代码:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    manager.stopUpdatingLocation()
    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
        (placemarks, error) -> Void in
        if placemarks!.count > 0 {
            self.latitude = (manager.location?.coordinate.latitude)!
            self.longitude = (manager.location?.coordinate.longitude)!
            print(self.latitude)
            print(self.longitude)
        } else {
            print("Error")
        }
    })
}

您已经看到了问题,因为您仍在继续更新您的位置,同时仍在进行反向地理编码调用。