【问题标题】:iOS and Swift: CLLocationManagerDelegate not updating location coordinates beyond the first locationiOS 和 Swift:CLLocationManagerDelegate 不更新第一个位置以外的位置坐标
【发布时间】:2016-01-30 09:27:35
【问题描述】:

使用以下代码,我的 currentLat 和 currentLong 不会更新到第一个位置之外。位置永远不会超过 1 项,而且总是完全相同。

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let loc: CLLocation = locations[locations.count - 1]
    currentLat = loc.coordinate.latitude
    currentLong = loc.coordinate.longitude
}

我一直在做的所有搜索都只展示了如果它根本不起作用,如何让它起作用,但这确实有效,但只有一次。

我希望它的工作方式是不断更新 GPS 坐标,并在位置更新时触发此委托。位置是否一直在更新?我认为这是由于“startUpdatingLocation()”的术语和存在“stopUpdatingLocation()”。我是否试图错误地使用它?

就像我说的,它是第一次工作,所以加载和启动都很好,权限是允许的,info.plist 有必要的条目。

【问题讨论】:

  • 您是否在 viewDidLoad 中正确调用了代理?
  • 是的,否则它不会第一次工作。这也是我有 startUpdatingLocation() 的地方
  • 第一次更新后尝试停止更新stopUpdatingLocation()放在let loc: CLLocation之前再调用更新位置。
  • 请查看给定的解决方案:Update user location objective-c and Swift

标签: ios swift cllocationmanager


【解决方案1】:

当您想要更新您的位置时,您应该在现有更新获得新位置后停止它。您可以在 didUpdateLocations: 方法中使用 stopUpdatingLocation() 来执行此操作。

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

    // This should match your CLLocationManager()
    locManager.stopUpdatingLocation()

    let loc: CLLocation = locations[locations.count - 1]
    currentLat = loc.coordinate.latitude
    currentLong = loc.coordinate.longitude
}

然后在您需要新位置时致电您的locManager.startUpdatingLocation()

【讨论】:

  • 我明白你在说什么。所以 startUpdatingLocation() 实际上只是一次使用,不会一直在后台运行。根据我的阅读,我认为它会不断更新位置,并且每次更新时,它都会执行这个委托。这可以解释为什么我获得第一个位置没有问题,但再也没有。我只在 viewDidLoad() 中调用 startupdatingLocation()。
  • 没错,想一想也有道理,一旦你得到了位置,你并没有停止它,所以基本上和第一次更新一样。我希望我在这个答案上得到绿色检查,干杯伙伴:)
  • 什么?那是什么? @LeoDabus 现在就杀吧。
  • 最优秀。这解决了我的问题。我遇到的所有示例都只获得了一次坐标,所以对于我想要做的事情来说,这个例子还不够清楚。现在对我来说很有意义,谢谢法哈德。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 2017-12-06
相关资源
最近更新 更多