swift如何获得当前高度在 ios 8?

标签: gps ios Swift
发布时间: 2017/3/6 23:30:39
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我很难找到设备的高度,需要在我的应用程序来显示高度如何能做到吗? 我已经试过了︰

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

什么都不显示...

解决方法 1:

其实你不调用正确的委托方法,拨打︰ locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) 但会给你你想要的就是 locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

所以,如果你确实执行 NSLocationWhenInUseUsageDescription 关键到您 Info.plist 文件和弹出窗口显示你只要你的函数中删除和添加这一,它应该工作︰

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
}

我也建议你来电 locationManager.stopUpdatingLocation() 这里面不委派功能。

希望这将帮助你 !

注︰这种语法是为 Swift 3.0,但我认为你只需要删除 _ 中的委托函数 Swift 2.2。

赞助商