简体   繁体   中英

How to get current altitude in ios 8?

I have trouble to find the altitude of the device, I need in my app to show the altitude How can I do that? I have tried that:

 var locationManager:CLLocationManager = CLLocationManager()

override func viewDidLoad() {

    super.viewDidLoad()
    self.locationManager = CLLocationManager()
    locationManager.requestWhenInUseAuthorization()
    self.locationManager.delegate = self
    self.locationManager.distanceFilter = kCLDistanceFilterNone
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.startUpdatingLocation()

}


func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
    var alt = newLocation.altitude
    print("\(alt)")
    manager.stopUpdatingLocation()
}

nothing show up....

Actually you are not calling the right delegate method, you are calling : locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) but the one that will give you what you want is locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) ,

So if you did implement the NSLocationWhenInUseUsageDescription key into your Info.plist file and if the popup is showing you just have to remove your function and add this one, it should work :

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let lastLocation = locations.last else {
        NSLog("error no last location")
        return
    }
    let altitude = lastLocation.altitude
     // Do what you want with your altitude
}

I also suggest you to call locationManager.stopUpdatingLocation() not inside this delegate function.

Hope this will help you !

Note : This syntax is for Swift 3.0, but I think that you just have to remove the _ in the delegate function for Swift 2.2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM