2016-07-25 43 views
3

我很难找到设备的高度,我需要在我的应用程序中显示高度我该怎么做? 我已经试过了:如何获得ios 8当前的高度?

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

您是否在'info.plist'中添加了'NSLocationAlwaysUsageDescription'键? – WMios

+0

你在你的info.plist中包含了“NSLocationAlwaysUsageDescription'键吗? – AtWork

+0

实际上OP是要求使用授权,所以他需要一个NSLocationInUseDescription,或者任何正在使用的版本。 –

回答

3

其实你是不是调用正确的委托方法,你在呼唤: 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的代理函数中删除_即可。

+0

它正在工作!它是英尺还是米? –

+0

根据[AppleDocumentation](https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocation_Class/index.html#//apple_ref/occ/instp/CLLocation/altitude), 'The以米为单位测量高度。 (只读)' – Chajmz