Swift CLLocationManager(didUpdateLocations) 调用过于频繁

标签 swift delegates mapkit core-location cllocationmanager

谁能解释一下,为什么我立即停止更新,但委托(delegate)方法“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")
            }
        })
    }
}

谢谢!

最佳答案

尝试将 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")
                }
            })
        }
    }

关于Swift CLLocationManager(didUpdateLocations) 调用过于频繁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35468872/

相关文章:

ios - 如何让 arc4random 在 swift 中选择 4 个不同的名称

ios - 在 Swift 中使用 MagicalRecord 实例化的向下转换 CoreData 实体

javascript - 我想知道 jquery 的委托(delegate)或 on(for delegate) 是如何工作的

ios - Xcode,有委托(delegate)方法自动包含类

ios - MapKit,使用按钮将图钉放在一个位置

ios - 如何在 Ios 中添加 customView xib 作为注释?

ios - VectorKit MapKit 堆栈溢出崩溃

macOS 上的 Swift : open Chrome with a URL as parameter

ios - UITapGestureRecognizer 点坐标

swift - Storyboard中的弹出窗口,如何处理委托(delegate)