【问题标题】:How do I display the altitude of the user in swift?如何快速显示用户的高度?
【发布时间】:2017-06-18 09:32:20
【问题描述】:

我正在尝试构建一个显示用户高度的应用程序,但 xCode 说 CLLocation 没有成员“高度”。我使用的代码是

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { self.Altitude.text = String(locations.altitude)}

【问题讨论】:

  • Locations 是一个位置数组,而数组没有属性altitude。您必须首先从数组中获取其中一个位置元素,例如 locations[0].altitude

标签: swift swift3 core-location


【解决方案1】:

Xcode 没有说“CLLocation”没有成员 'altitude'”,而是说“[CLLocation] 没有成员 'altitude'”。

locationsCLLocation 对象的数组,并且(因为它是一个数组)没有名为 altitude 的属性。

您需要做的是从数组中提取一个值并使用它来访问高度。

你可能想做这样的事情:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
  guard let altitude = locations.last?.altitude else { return }
  self.Altitude.text = String(altitude)
}

由于这是一个面向用户的字符串,您应该使用 LengthFormatter 正确格式化它。

一个小风格说明:变量名(如self.Altitude应该小写,只有类型是PascalCase)。

【讨论】:

  • 为什么是“.last”?我怎么会知道这个?
  • 因为它是最近的位置,而且(通常)是您想要使用的位置。
  • 我明白了。无论如何,你也可以使用经理的位置(这是我最终做的,因为我喜欢知道我使用的代码是如何工作的)
  • 好吧,这一切都在文档中developer.apple.com/documentation/corelocation/… 现在你也知道上面的代码是如何工作的了;)
  • 对于特定设置使用location属性也可以给你旧数据:It is always a good idea to check the timestamp of the location stored in this property. If the receiver is currently gathering location data, but the minimum distance filter is large, the returned location might be relatively old. If it is, you can stop the receiver and start it again to force an update. from developer.apple.com/documentation/corelocation/…
【解决方案2】:
You can get Altitude from reverse geocoding in swift for this you can use locationManager and locationManager didUpdateLocations method. 

Step 1: Add below Code in ViewdidLoad method:- 

let locationManager = CLLocationManager()
locationManager.headingFilter = 1
locationManager.delegate = self
locationManager.startUpdatingHeading()


Step 2: Use didUpdateLocations Method:- 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
 guard let altitude = locations.last?.altitude else { return }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多