Search code examples
iosswiftgpscllocation

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


I've been trying to get the altitude from a CLLocation that i get from from the CoreLocation framework using the following code:

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()
    }
}
}

So if I only request the location I'm able to get the gpsResult.text value and it works correctly but when I try to access the altitude I get an error:

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

The thing is as per apple's reference that selector should exist. I went through the posts here and the net and I tried their code but all of them failed.

Does anyone haven an idea what's goig on?

Thanks.


Solution

  • According to Apple's documentation CLLocationManagerDelegate the locations parameter of didUpdateLocations gives:

    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.

    So you can access the most recent location via the last element in 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()
    }