我可以获取纬度和经度,但无法访问 SWIFT 中的 GPS 高度信息

I can get Lat and Long but I can't access the GPS altitude info in SWIFT

我一直在尝试使用以下代码从 CoreLocation 框架中获取的 CLLocation 获取海拔高度:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

/*
Note: This needs to be added to the info.plist file for this to work:

<key>NSLocationUsageDescription</key> <string>Your message</string> <key>NSLocationAlwaysUsageDescription</key> <string>Your message</string> <key>NSLocationWhenInUsageDescription</key>
<string>Your message</string>
*/

@IBOutlet weak var gpsResult: UILabel!
@IBOutlet weak var altitudeLabel: UILabel!


var manager:CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    manager = CLLocationManager()
        manager.delegate = self
        manager.distanceFilter = kCLDistanceFilterNone
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestAlwaysAuthorization()
        manager.startUpdatingLocation()

}

func locationManager(manager:CLLocationManager!, didUpdateLocations myLocations:CLLocation) {
    if manager != nil {
        var alt:CLLocationDistance = myLocations.altitude

        gpsResult.text = "locations = \(myLocations)"
        altitudeLabel.text = "GPS Altitude: \(Double(alt))"
        // manager.stopUpdatingLocation()
    }
}
}

因此,如果我只请求位置,我能够获得 gpsResult.text 值并且它工作正常,但是当我尝试访问高度时,我收到错误消息:

 'NSInvalidArgumentException', reason: '-[__NSArrayM altitude]: unrecognized selector sent to instance 0x17404dcb0'

根据apple's reference,选择器应该存在。 我浏览了这里和网上的帖子,并尝试了他们的代码,但都失败了。

有谁知道发生了什么事吗?

谢谢。

根据 Apple 的文档 CLLocationManagerDelegate didUpdateLocationslocations 参数给出:

An array of CLLocation objects containing the location data. This array always contains at least one object representing the current location. If updates were deferred or if multiple locations arrived before they could be delivered, the array may contain additional entries. The objects in the array are organized in the order in which they occurred. Therefore, the most recent location update is at the end of the array.

因此您可以通过数组中的最后一个元素访问最近的位置:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    let location = locations.last

    gpsResult.text = "locations = \(location)"
    altitudeLabel.text = "GPS Altitude: \(location.altitude)"
    // manager.stopUpdatingLocation()
}